Lập trình website Python với Django Framework

Leave a Comment

Tạo website hello world đơn giản với Django Framework


Python không có sẵn khả năng làm web, chính vì thế, chúng ta cần phải có một số module nhất định để lập trình web với Python.
django_helloworld (7)

Với nhu cầu ngày càng đa dạng, lập trình viên nên chuyển sang một số framework Python như Django hay Flask để có thể cho ra các ứng dụng web phức tạp.

Các dịch vụ nổi tiếng như Instagram, Reddit, Quora và Disqus đều được phát triển trên nền Python.


Django framework là gì?


Django là một web framework khá nổi tiếng được viết hoàn toàn bằng ngôn ngữ Python. Nó không phải là một micro-framework như Flask, mà là một framework với đầy đủ các thư viện, module hỗ trợ các web-developer.

Django được so sánh khá nhiều với Ruby on Rails.


Tại sao nên dùng Django framework


Nếu bạn đang muốn xây dựng 1 website một cách nhanh nhất, thì Django luôn là một trong những lựa chọn hàng đầu mà bạn nên cân nhắc.

Django framework có đầy đủ các yếu tố phục vụ cho người bắt đầu(starter):


  • Nhanh: Chỉ vài dòng code là bạn có ngay trang web. Do Django có sẵn các thư viện về user authentication, content admin, site maps, RSS feed v.v…

  • Đảm bảo về tính bảo mật: Hạn chế các lỗi bảo mật thông thường như SQL Injection, cross-site scripting, cross-site request forgery hay clickjacking nữa.

  • Khả năng mở rộng tốt: Django framework có thể đáp ứng lượng traffic lớn, nghĩa là bạn không cần phải lo lắng về khả năng mở rộng sản phẩm của mình nữa.

  • Tính linh hoạt: Xây dựng CMS, hoặc Ecommerce Website, hay kể cả Social Network, Scientific Computing Platforms, tất cả đều có thể với Django framework.

Xem thêm: Hướng dẫn cài đặt Python trên Windows Linux đơn giản


Cài đặt Django trên Windows


  • Nhấn tổ hợp phím Window + R,

  • Gõ cmd nhấn enter để mở một cửa sổ terminal, sau đó gõ:

pip install django

Cài đặt Django trên Linux, Mac


  • Tổ hợp phím Ctrl + Alt + T để mở Terminal

  • Gõ:

sudo apt-get install python3-django

Chờ một lát để quá trình cài đặt diễn ra.

Bắt tay vào chủ đề chính nào, bây giờ mình sẽ


Hướng dẫn tạo 1 website hello world đơn giản với Django Framework


Công cụ:


  • Visual Studio Code

  • Python Extension

Đầu tiên, bạn tạo folder project đặt tên helloworldpython
django_helloworld (2)

Tại thư mục đó mở Visual Studio Code (đã cài extension Python)


Tạo môi trường ảo (virtual environment) để Django được cài vào đó.


Sử dụng môi trường ảo sẽ tránh cài đặt Django vào môi trường Python global và cung cấp cho bạn quyền kiểm soát chính xác các thư viện được sử dụng trong một ứng dụng. Một môi trường ảo cũng giúp bạn dễ dàng tạo tệp requirements.txt (giống file pom.xml trong maven Java)

Thay vì mỗi lần cài bạn phải cài từng thư viện một. Bạn không thể nhớ hết được và phải gõ nhiều lần. File requirements.txt sẽ giúp bạn tránh điều này.

Bạn có thể tạo file requirements.txt thủ công nhưng mình khuyến nghị dùng lệnh  pip freeze tạo tự động dựa trên các thư việc đã được cài trong môi trường ảo.
Tạo môi trường ảo(virtual environment) với tên env:


# macOS/Linux
sudo apt-get install python3-venv # If needed
python3 -m venv env
# Windows
python -m venv env

django_helloworld (3)
Tạo file requirements.txt:


  • Nhấn Ctrl+Shift+` để mở terminal.

  • Gõ: pip freeze > requirements.txt và chèn Django==2.2.4 vào file đó.

Kích hoạt môi trường ảo:

Trong Visual Studio Code, View > Command Palette or (Ctrl+Shift+P) > Chọn Python: Select Interpreter

Chọn env vừa tạo
django_helloworld (4)
Sau khi kích hoạt môi trường bạn sẽ thấy (env) trước dòng lệnh terminal
Cài đặt thư viện vào môi trường ảo vừa chọn:
pip install -r requirements.txt

Nếu bạn gặp lỗi SSL thì chạy lệnh sau:
pip install -r requirements.txt --trusted-host pypi.org
django_helloworld (5)


Hoặc bạn không dùng file requirements.txt thì install django với lệnh: pip install django


Tạo Django Project


django-admin startproject web_project .

dấu . cuối để cài project vào ngay thư mục hiện tại.
django_helloworld (6)

Sau khi chạy lệnh trên sẽ có 1 số file:
manage.py: File quản trị dòng lệnh Django cho dự án. Ví dụ khi bạn start project django: python manage.py runserver

Một thư mục con có tên web_project, chứa các tệp sau:


  • __init__.py: một tệp trống cho Python biết thư mục này là gói Python.

  • settings.py: File cấu hình cho project Django mà bạn sẽ sửa đổi trong quá trình phát triển ứng dụng web.

  • urls.py: chứa danh sách url cho project Django giống với controller bên Java, mà bạn cũng sửa đổi trong quá trình phát triển.

  • wsgi.py: File cấu hình máy chủ web tương thích WSGI. Bạn không cần để ý nó trong bài viết này.

Chưa cần làm gì hết, hãy chạy project của bạn lên nào:
python manage.py runserver

Mặc định là port 8000. Bạn muốn port khác 5000 chẳng hạn, dùng lệnh này:  python manage.py runserver 5000

 

Giữ Ctrl và nhấn vào link http://127.0.0.1:8000/ để chạy trang web.

Tèn ten! Một trang web khá đẹp mặc định của Django xuất hiện !!!
django_helloworld (7)

Bây giờ chúng ta muốn in ra dòng chữ Hello, Django! from ShareEverythings.com thay vì trang mặc định, làm như sau.


Tạo app cho project Django


Gõ:


python manage.py startapp helloqlam

Sau khi chạy lệnh, bạn sẽ thấy có 1 thư mục là helloqlam, trong đó có:


  • admin.py: quản lí trang admin cho app

  • models.py: model của app

  • apps.py: cấu hình cho app, ví dụ tên định danh của app

  • views.py: chứa các hàm xử lí khi url hay controller gọi, file này giống service bên Java

Chỉnh sửa file views.py, để in ra hello world ở home page


from django.shortcuts import render
from
django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django! from ShareEverythings.com")

Tạo file urls.py với nội dung bên dưới để gọi hàm home trong file views.py trên


from django.urls import path
from helloqlam import views
urlpatterns = [
path("", views.home, name="home"),
]

Trong thư mục web_project, chỉnh sửa file urls.py,để gọi urls từ app helloqlam


from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("helloqlam.urls")),
]

Lưu hết lại, và chạy project nào:
python manage.py runserver

Mở trình duyệt với: http://127.0.0.1:8000/. Bạn sẽ thấy Hello, Django! from ShareEverythings.com
django_helloworld (1)


Video hướng dẫn chi tiết Tạo website Django Framework trong 5 phút:




Xong rồi! Mình đã hướng dẫn các bạn lập trình website Python với Django Framework thông qua hello world app đơn giản.

Bạn có thắc mắc thì bình luận bên dưới nhé!



Django Framework, Học hành, Lập trình
Lập trình, Python
Xem Tiếp

Hướng dẫn cài đặt môi trường lập trình Python

Leave a Comment

Cài đặt môi trường lập trình Python cơ bản


Python là một ngôn ngữ lập trình thông dịch (interpreted), hướng đối tượng (object-oriented), và là một ngôn ngữ bậc cao (high-level). Python hỗ trợ các module và gói (packages), khuyến khích chương trình module hóa và tái sử dụng mã.


Python là ngôn ngữ mã nguồn mở


  • Cài đặt Python dùng giấy phép nguồn mở ngay cả trong việc thương mại.

Python là ngôn ngữ có khả năng chạy trên nhiều nền tảng. 

  • Python có cho mọi hệ điều hành: Windows, Linux/Unix, Mac…


Python dễ dàng kết nối với các thành phần khác:



  • Có thể viết các thư viện trên C/C++ để nhúng vào Python và ngược lại.



Python rất đơn giản và dễ học


  • Python có cộng đồng lập trình rất lớn, hệ thống thư viện chuẩn, và cả các thư viện mã nguồn mở được chia sẻ trên mạng.

Cài đặt Python trên Windows



Tải về và cài đặt Python cho windows


Python 3.7.2 là bản mới nhất hiện tại bài viết

Việc cần làm đầu tiên của chúng ta là cài đặt môi trường làm việc của Python lên máy tính.


  1. Truy cập https://www.python.org/ download phiên bản mới nhất của python về máy.

  2. Tải về được 1 file name python-x.x.x.exe, double click và cài đặt như bình thường,pythonsetup

  3. Trong quá trình cài đặt nhớ tick vào dòng Add python 3.x to PATH để sau đó đỡ phải mở Environment Variables để cài đặt Path cho Python.

Kiểm tra python đã cài đặt thành công hay chưa bằng cách


  1. Nhấn Window + R,

  2. Gõ cmd, một màn hình terminal xuất hiện, các bạn

  3. Gõ: python

cmd


Cài đặt Python 3.6 trên Linux


Mở Terminal: Ctrl + Alt + T


sudo add-apt-repository ppa:jonathonf/python-3.6

Nhập password nếu có.
Nhập tiếp các lệnh:


sudo apt-get update
sudo apt-get install python3.6

Nếu gặp lỗi

E: Could not get lock /var/lib/dpkg/lock – open (11: Resource temporarily unavailable)

E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
thì nhập


sudo rm /var/lib/apt/lists/lock
sudo rm /var/cache/apt/archives/lock
sudo rm /var/lib/dpkg/lock
sudo dpkg --configure -as

Cài đặt thành công. Bạn đã cài đặt 1 loạt các gói python. Bây giờ chúng ta kiểm tra các bản đã cài.

Bạn sẽ có 3 phiên bản Python, Dùng các lệnh để xem phiên bản.
python-versions-600x143
Mình đã hướng dẫn các bạn cài đặt python trên Windows và Linux. Chúc các bạn thành công !

 



Django, Flask, Học hành, Lập trình, Linux
Lập trình, Python
Xem Tiếp

Thao tác với file .properties Spring framework

Leave a Comment

Cách đọc ghi file .properties Spring framework


Ở bài này mình sẽ làm ví dụ về các cách đọc và ghi thông tin vào file .properties với Spring Boot.


1. File application.properties dùng để lưu cái gì?


File properties trong Java được sử dụng để lưu trữ dữ liệu cấu hình dự án hoặc các thông số cài đặt cho dự án như thông số port, mail, jdbc connection…

Thông tin trong file Properties là các cặp key/value cấu hình cho dự án của bạn. Trong mỗi cặp key/value đều là các giá trị kiểu String.
Ví dụ file application.properties:


# Connection url for the database
spring.datasource.url=jdbc:mysql://localhost:3306/myemployee?useSSL=false
# MySQL username and password
spring.datasource.username=root
spring.datasource.password=root

2. Đọc properties file


Các cách đọc thông tin từ file properties với Spring Framework.


Sử dụng annotation @Value


Cách đơn giản nhất là sử dụng annotation @Value để lấy giá trị trong file application.properites vào thuộc tính của các Spring Bean.


// file application.properties
message=ShareEverythings.com
//java class
package qlam.com.springboothello.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import qlam.com.springboothello.bean.GlobalConfig;
@Controller
public class Controller
@Value("$message")
private String message;

Sử dụng annotation @PropertySource để đọc những file .properites khác application.properties


Ví dụ đọc từ file global.properties thay vì application.properties


// file global.properties
website=shareeverythings.com
facebook=facebook.com/xmaster699
name=qlam
//java
package qlam.com.springboothello.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:global.properties")
public class GlobalConfig
@Value("$name")
private String name;
@Value("$website")
private String website;
@Value("$facebook")
private String facebook;

Sử dụng annotation @ConfigurationProperties


Annotation @ConfigurationProperties sẽ tự động mapping thuộc tính của bean với các giá trị trong file .properties. Lưu ý: tên tương ứng phải giống nhau.


package qlam.com.springboothello.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties
@PropertySource("classpath:global.properties")
public class GlobalConfig
private String name;
private String website;
private String facebook;

Sử dụng Environment


Bạn chỉ cần dùng biến Environment là có thể lấy các message trong file .properties.

Mặc định Environment lấy message từ trong file application.properties, nếu bạn muốn nó đọc từ các file khác thì dùng kèm với @PropertySource như mục trước.


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
@Service
public class Service
@Autowired
Environment env;
public void hello()
System.out.println(env.getProperty("message"));


Validate dữ liệu từ file properties


@ConfigurationProperties Hỗ trợ validate dữ liệu với javax.validation

Để validate dữ liệu ta sử dụng annotation @Validated ở đầu class và các annotation validate ở mỗi field ví dụ dùng @NotEmpty:


// File GlobalConfig.java
package qlam.com.springboothello.bean;
import javax.validation.constraints.NotEmpty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Component
@ConfigurationProperties
@PropertySource("classpath:global.properties")
@Validated
public class GlobalConfig
@NotEmpty
private String name;
private String website;
private String facebook;

Nếu dữ liệu không hợp lệ thì ứng dụng sẽ thông báo lỗi:


***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under '' to qlam.com.springboothello.bean.GlobalConfig failed:
Property: .name
Value:
Origin: "name" from property source "class path resource [global.properties]"
Reason: must not be empty
Action:
Update your application's configuration

Đọc properties file từ classpath


Giả sử file “application.properties” nằm trong thư mục gốc của classpath (Khi build dự án sẽ có thư mục target/classes/application.properties )


remote.server=192.168.1.100
remote.server.port=8080
remote.user=qlam
remote.password=qlam

package qlam.example;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class LoadPropertiesFromClasspath
public static void main(String[] args)
Properties prop = new Properties();
InputStream input = null;
try
String filename = "application.properties";
input = LoadPropertiesFromClasspath.class.getClassLoader().getResourceAsStream(filename);
if (input == null)
System.out.println("Sorry, unable to find " + filename);
return;

// load a properties file from class path, inside static method
prop.load(input);
// get the property value and print it out
prop.entrySet().forEach(e -> System.out.println(e.getKey() + " : " + e.getValue()));
catch (IOException ex)
ex.printStackTrace();
finally
if (input != null)
try
input.close();
catch (IOException e)
e.printStackTrace();





Kết quả chạy:


remote.server : 192.168.1.100
remote.server.port : 8080
remote.user : qlam
remote.password : qlam

Đọc các file properties phức tạp


// file menu.properties
#App
app.menus[0].title=Home
app.menus[0].name=Home
app.menus[0].path=/home
app.menus[1].title=Login
app.menus[1].name=Login
app.menus[1].path=/login

Hoặc với file yaml. Xem bài thao tác với file .yml


// file menu.yml
app:
menus:
- title: Home
name: Home
path: /home
- title: Login
name: Login
path: /login

Lưu ý: annotation @ConfigurationProperties hỗ trợ cả file.properties và file.yml.


package qlam.com.springboothello.bean;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("app") // prefix app, find app.* values
@PropertySource("classpath:menu.properties")
public class MenuConfig {
private List<Menu> menus = new ArrayList<>();
public List<Menu> getMenus()
return menus;

public void setMenus(List<Menu> menus)
this.menus = menus;

public static class Menu
private String name;
private String path;
private String title;
@Override
public String toString()
return "Menu" + "name='" + name + '\'' + ", path='" + path + '\'' + ", title='" + title + '\'' + '';


Demo tổng hợp


File Properties:



//File application.properties
message=ShareEverythings.com
// File menu.properties
#App
app.menus[0].title=Home
app.menus[0].name=Home
app.menus[0].path=/home
app.menus[1].title=Login
app.menus[1].name=Login
app.menus[1].path=/login
//File global.properties
website=shareeverythings.com
facebook=facebook.com/xmaster699
name=qlam


File Controller:


//File BaseController.java
package qlam.com.springboothello.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import qlam.com.springboothello.bean.GlobalConfig;
import qlam.com.springboothello.bean.MenuConfig;
@Controller
public class BaseController
@Autowired
private GlobalConfig globalConfig;
@Autowired
private MenuConfig menuConfig;
@Value("$message")
private String message;
@RequestMapping("/")
public String index(Model model)
model.addAttribute("name", globalConfig.getName());
model.addAttribute("website", globalConfig.getWebsite());
model.addAttribute("facebook", globalConfig.getFacebook());
model.addAttribute("message", message);
model.addAttribute("menus", menuConfig.getMenus());
return "index";



File view:


// File index.html
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot - Share Everything </title>
</head>
<body>
<h1>Spring Boot Properites file</h1>
<table>
<tr>
<td>Name:</td>
<td><p th:text="$name">Default Name</p></td>
</tr>
<tr>
<td>Website:</td>
<td><p th:text="$website">Default Website</p></td>
</tr>
<tr>
<td>Facebook:</td>
<td><p th:text="$facebook">Default Facebook</p></td>
</tr>
<tr>
<td>Message:</td>
<td><p th:text="$message">Default Message</p></td>
</tr>
Menu:
<ul th:if="$menus != null && !menus.empty">
<li th:each="menu: $menus" th:text="$menu"></li>
</ul>
</table>
</body>
</html>


Kết quả:
properties file


3. Ghi dữ liệu động vào properties file


Thiết lập giá trị của thuộc tính và lưu nó vào properties file có tên là application.properties


package qlam.properties.example;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class WriteProperties
public static void main(String[] args)
Properties prop = new Properties();
OutputStream output = null;
try
output = new FileOutputStream("application.properties");
// set the properties value
prop.setProperty("remote.server", "192.168.1.100");
prop.setProperty("remote.server.port", "8080");
prop.setProperty("remote.user", "qlam");
prop.setProperty("remote.password", "qlam");
// save properties to project root folder
prop.store(output, null);
catch (IOException io)
io.printStackTrace();
finally
if (output != null)
try
output.close();
catch (IOException e)
e.printStackTrace();





Sau khi run, file application.properties sẽ được sinh ra với nội dung như sau:


remote.server=192.168.1.100
remote.server.port=8080
remote.user=qlam
remote.password=qlam

Xong mình đã hướng dẫn cách đọc và ghi thông tin vào file .properties với Spring Boot. Bạn nào thắc mắc gì thì hãy bình luận bên dưới nhé !



Học hành, Lập trình, Spring Framework
Java, Lập trình
Xem Tiếp

Java Streams - Sự khác nhau giữa Collections và Streams

Leave a Comment

Java Streams – Sự khác nhau giữa Collections và Streams


Streams là một bổ sung mới trong thư viện Collections API của Java 8. Java streams API xử lý tuần tự các element cho collection tương tự Linq trong C sharp hay câu query trong SQL.


Xét ví dụ:

Tính tổng lương của tất cả Employee trong query SQL.

Code SQL:


SELECT SUM(salary) FROM Employee

Câu lệnh trên tự động trả về tổng lương của tất cả Employee mà không cần phải thực hiện bất kì tính toán gì ở phía đầu cuối developer(Bình thường thì sẽ SELECT tất cả các Employee, sau đó dùng code Java để duyệt và tính tổng của tất cả Employee).

Tương tự vấn đề trên, khi sử dụng Collections trong Java, chúng ta thực hiện các vòng lặp và thực hiện lại các đoạn kiểm tra. Giả sử muốn tính tổng lương của các employee có role = ‘Developer’ từ 1 danh sách chúng ta phải thực hiện lặp tất cả các phần tử, kiểm tra phần tử đó có role = ‘Developer’ rồi cộng lại.

Code thường:


public static final String ROLEDEVELOPER = "Developer";
public double sumSalaryDeveloper(List<Employee> listEmployee)
double sumSalary = 0;
for (Employee emp : listEmployee)
if (emp.getRole().equals(ROLEDEVELOPER))
sumSalary += emp.getSalary();


return sumSalary;

Code Java Stream:


public static final String ROLEDEVELOPER = "Developer";
public double sumSalaryDeveloper(List<Employee> listEmployee)
return listEmployee.stream().filter(p -> p.getRole().equals(ROLEDEVELOPER)).mapToDouble(p -> p.getSalary()).sum();

Ngắn ngọn, dễ hiểu như query SQL đúng không nào. Như vậy, bạn có thể hiểu stream đại diện cho một collection được xử lý tuần tự các phần tử và hỗ trợ rất nhiều loại operation để tính toán dựa trên những element của collection đó (sum, avg, toMap, toList …)


So sánh sự khác nhau giữa Collections và Streams


Lưu trữ – Java Stream không giống như các Collection không lưu trữ bất kỳ dữ liệu nào.
Tính toán – Các phần tử trong các Collection được tính toán trước khi được thêm vào Collection, trong khi các phần tử stream được tính theo yêu cầu nếu chúng được sử dụng.
Kích thước – Collection chứa số lượng phần tử hữu hạn, trong khi Stream có khả năng vô hạn.
Mức tiêu thụ – Các phần tử trong Stream chỉ có thể được sử dụng một lần, tương tự như iterator. Các phần tử trong Collection có thể được dùng nhiều lần như mong muốn.
Iteration – Việc lặp lại trên các collection được thực hiện bên ngoài (bởi người dùng) trong khi Stream sử dụng lặp lại nội bộ và xử lý việc này cho bạn. Do đó việc debug khá khó khăn trên Streams do việc lặp nội bộ.


Hướng dẫn dùng Streams cơ bản


Tạo 1 empty stream


Method empty() được sử dụng để tạo 1 empty stream:


Stream<String> streamEmpty = Stream.empty();

empty() thường được dùng khi khởi tạo để tránh việc trả về null cho các Stream


public Stream<String> streamOf(List<String> list) 
return list == null

Tạo stream từ collection (Stream of Collection)


Stream cũng có thể được tạo từ bất kì kiểu collection nào (bao gồm: Collection, List, Set …):


Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> streamOfCollection = collection.stream();

Stream of Array


Stream cũng có thể được tạo từ 1 array hoặc 1 phần của array:


Stream<String> streamOfArray = Stream.of("a", "b", "c");
String[] arr = new String[]"a", "b", "c";
Stream<String> streamOfArrayFull = Arrays.stream(arr);
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);

Stream.builder()


Stream.builder() được sử dụng khi muốn thêm mới 1 phần vào bên phải stream.


Stream<String> streamBuilder =
Stream.<String>builder().add("a").add("b").add("c").build();

Stream.generate()


Phương thức generate() chấp nhận một Supplier<T> cho các phần tử được tạo ra. Số phần tử được tạo ra là vô hạn nên cần phải dùng lệnh .limit() để giới hạn số phần tử được tạo ra.

Ví dụ đoạn code dưới đây sẽ tạo ra liên tục 10 String có giá trị là “shareeverythings.com”


Stream<String> streamGenerated =
Stream.generate(() -> "shareeverythings.com").limit(10);

Stream.iterate()


1 cách khác để tạo ra 1 stream vô hạn là sử dụng method iterate():


Stream<String> streamIterated = Stream.iterate("qlamxmaster", n -> n + 1).limit(5);
List<String> listIterated = streamIterated.collect(Collectors.toList());
System.out.println(listIterated);

Kết quả:



  • [qlamxmaster, qlamxmaster1, qlamxmaster11, qlamxmaster111 …]


Stream of String


Stream<String> streamOfString =
Pattern.compile("_ ").splitAsStream("a, b, c");

Stream of File


Path path = Paths.get("C:\\file.txt");
Stream<String> streamOfStrings = Files.lines(path);
Stream<String> streamWithCharset =
Files.lines(path, Charset.forName("UTF-8"));

Các ví dụ, method thường dùng với Stream


Chuyển 1 Stream sang Collection hoặc array:


  • Chúng ta có thể dùng stream collect() để tạo 1 List, Set, Map từ stream.

Stream<Integer> intStream = Stream.of(1,2,3,4);
List<Integer> intList = intStream.collect(Collectors.toList());
System.out.println(intList); //prints [1, 2, 3, 4]


intStream = Stream.of(1,2,3,4); //stream bị đóng nên cần khởi tạo lại
Map<Integer,Integer> intMap = intStream.collect(Collectors.toMap(i -> i, i -> i+10));
System.out.println(intMap); //prints 1=11, 2=12, 3=13, 4=14


  • Dùng stream toArray() để tạo 1 array từ stream


Stream<Integer> intStream = Stream.of(1,2,3,4);
Integer[] intArray = intStream.toArray(Integer[]::new);
System.out.println(Arrays.toString(intArray)); //prints [1, 2, 3, 4]


Stream.filter()


Stream.filter() Trả về 1 stream đã lọc các phần tử khớp với điều kiện Predicate



Predicate<Integer> p = num -> num % 2 == 0;
List<Integer> list = Arrays.asList(3,4,6);
list.stream().filter(p).forEach(e -> System.out.print(e+" "));


Kết quả:



  • 4 6


Stream.allMatch(), Stream.anyMatch() and Stream.noneMatch()


allMatch(): trả về true nếu tất cả các phần tử khớp với Predicate.
anyMatch(): trả về true nếu có ít nhất 1 phần tử khớp với Predicate.
noneMatch(): trả về true nếu không có phần tử nào khớp với Predicate.

Ví du:



Predicate<Integer> p = num -> num % 2 == 0;
List<Integer> list = Arrays.asList(3,5,6);
System.out.println("allMatch:" + list.stream().allMatch(p));
System.out.println("anyMatch:" + list.stream().anyMatch(p));
System.out.println("noneMatch:" + list.stream().noneMatch(p));


Kết quả:



  • allMatch:false

  • anyMatch:true

  • noneMatch:false


Stream.findAny() and Stream.findFirst()


findAny(): Trả về 1 phần tử bất kì của stream.
findFirst(): Trả về phần tử đầu tiên của stream.

Ví dụ:



List<String> list = Arrays.asList("G","B","F","E");
String any = list.stream().findAny().get();
System.out.println("FindAny: "+ any);
String first = list.stream().findFirst().get();
System.out.println("FindFirst: "+ first);


Kết quả:



  • FindAny: G

  • FindFirst: G


Stream.distinct()


Stream.distinct() trả về 1 stream với các phần tử riêng biệt (không trùng nhau)



List<Integer> list = Arrays.asList(3,4,6,6,4);
System.out.print("Distinct elements: ");
list.stream().distinct().forEach(p -> System.out.print(p + ", "));


Kết quả:



  • Distinct elements: 3, 4, 6,


Stream map()


Sử dụng map() để map (ánh xạ) mỗi phần tử của stream sang 1 giá trị tương ứng. Ví dụ chuyển các string của 1 list sang chữ hoa:


Stream<String> names = Stream.of("qlamxmaster", "Java", "shareeverythings.com");
System.out.println(names.map(s ->
return s.toUpperCase();
).collect(Collectors.toList()));
//prints [QLAMXMASTER, JAVA, SHAREEVERYTHINGS.COM]

Stream.max() and Stream.min()


max(): tìm phần tử có giá trị lớn nhất dựa theo Comparator.
min(): tìm phần tử có giá trị nhỏ nhất dựa theo Comparator.

Ví dụ:



List<String> list = Arrays.asList("G","B","F","E");
String max = list.stream().max(Comparator.comparing(String::valueOf)).get();
System.out.println("Max:"+ max);
String min = list.stream().min(Comparator.comparing(String::valueOf)).get();
System.out.println("Min:"+ min);


Kết quả:



  • Max:G

  • Min:B


Một số lưu ý với Stream Java


Không tái sử dụng(Reuse) với stream: Stream java không thể tái sử dụng lại:



Stream<String> names = Stream.of("qlamxmaster", "java", "shareeverythings.com");
names.forEach(p -> System.out.print(p + " ")); // print: qlamxmaster java shareeverythings.com
names.forEach(p -> System.out.print(p + " ")); // exception: Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed


Cách xử lý: khởi tạo lại stream hoặc dùng Supplier:



Stream<String> names = Stream.of("qlamxmaster", "java", "shareeverythings.com");
names.forEach(p -> System.out.print(p + " ")); //print: qlamxmaster java shareeverythings.com
// Khởi tạo lại stream
names = Stream.of("qlamxmaster", "java", "shareeverythings.com");
names.forEach(p -> System.out.print(p + " "));  //print: qlamxmaster java shareeverythings.com
// dùng supplier:
Supplier<Stream<String>> streamSupplier = () -> Stream.of("qlamxmaster", "java", "shareeverythings.com");
streamSupplier.get().forEach(p -> System.out.print(p + " ")); //print: qlamxmaster java shareeverythings.com
streamSupplier.get().forEach(p -> System.out.print(p + " ")); //print: qlamxmaster java shareeverythings.com


References: http://bigdatums.net/2017/10/18/introduction-to-java-streams/ | https://stackjava.com/java8/stream-api-la-gi-stream-api-trong-java-8.html



Học hành, Lập trình
Java, Lập trình
Xem Tiếp

Hướng dẫn tạo thanh toán Paypal với Spring Boot + Thymeleaf

Leave a Comment

Hướng dẫn tạo thanh toán Paypal với Spring Boot + Thymeleaf


Nếu bạn chưa biết về phương thức thanh toán qua Paypal thì chúng ta tìm hiểu chút về phương thức thanh toán qua Paypal nhé!


paypal9


1. Paypal là gì?


Paypal được hiểu là một cổng thanh toán trực tuyến, chuyển tiền quốc tế (dịch vụ trung gian) giúp bạn thanh toán khi mua sắm trực tuyến quốc tế, hoặc nhận chi trả từ tài khoản nước ngoài về ngân hàng tại Việt Nam.

Là công cụ thay thế các phương thức giao dịch chuyển tiền truyền thống như thư/lệnh chuyển tiền, SEC, Western Union…

Paypal hoạt động trên nền thương mại điện tử thông qua internet, và thu phí khi phát sinh giao dịch chuyển – rút tiền. Với tốc độ phát triển không ngừng của thanh toán trực tuyến, ngày nay Paypal  đem lại rất nhiều lợi ích cho người sử dụng như: an toàn, nhanh chóng.


2. Có mấy loại tài khoản tại Paypal – đọc thêm


Có 2 loại tài khoản:

– Personal: Dành cho khách hàng cá nhân. Bạn bị giới hạn nhận – gửi tiền trong 1 tháng, giới hạn IP quốc gia đăng nhập. Ưu điểm của loại này là tỉ lệ giới hạn thấp.

– Business: Dành có các công ty , tổ chức hay nhóm cá nhân chuyển tiền với số lượng lớn. Đặc điểm của nó là không bị giới hạn tiền nhận, gửi. Có thể đăng nhập tài khoản từ nhiều IP mà không sợ bị giới hạn, ví dụ bạn có thể dùng IP Việt Nam để đăng nhập.

Bạn có thể tìm hiểu cách thanh toán với paypal thêm trên google.


3. Yêu cầu project Paypal payment




Sau đây là một số thứ cần có trước khi bắt tay vào lập trình thanh toán Paypal với Spring Boot và Thymeleaf engine.
Yêu cầu quan trọng:


  • Bạn đã có tài khoản Paypal. Nếu chưa có hãy tìm hiểu cách đăng kí Paypal trên mạng nhé! Trong quá trình đăng kí Paypal gặp khó khăn hãy comment bên dưới nhé!

Các công nghệ sử dụng:


  • Spring Boot

  • Thymeleaf engine

  • Paypal SDK for JAVA

Các công cụ phần mềm cần:


  • JDK 1.8 or later

  • Maven 3 or later

  • Eclipse + Plugin spring suite tool (STS)

Để làm được Project này chúng ta có 2 giai đoạn: Tạo app trên developer.paypal.com và code project spring boot thôi 😀


4. Tạo app trên developer.paypal.com


Đầu tiên chúng ta tạo app trên developer.paypal.com để lấy Client ID và Secret App

Đăng nhập vào https://developer.paypal.com/


paypal1


paypal2


Vào Dashboard, Chọn Create App


paypal2(1)


paypal3


Sau khi tạo app xong chúng ta sẽ được Client ID và Secret của app đó.


paypal4


Sau đây mình sẽ Hướng dẫn lập trình thanh toán Paypal với Spring Boot và Thymeleaf engine.


5. Tạo project Spring Boot + Thymeleaf với STS tool


Tạo project Spring Boot Starter


paypal5


Chọn như hình:


paypal6paypal7


Copy ClientID và SerectID vào File application.properties


paypal8


server.port: 8080
spring.thymeleaf.cache=false
#Paypal config
paypal.mode=sandbox
paypal.client.app=xxx-yourcode
paypal.client.secret=xxx-yourcode

Tạo các package: com.qlam.config, com.qlam.controller, com.qlam.service, com.qlam.utils

File pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qlam</groupId>
<artifactId>paypalpayment</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>paypalpayment</name>
<description></description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.paypal.sdk</groupId>
<artifactId>rest-api-sdk</artifactId>
<version>1.4.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Tạo class PaypalConfig.java trong package com.qlam.config


package com.qlam.config;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.OAuthTokenCredential;
import com.paypal.base.rest.PayPalRESTException;
@Configuration
public class PaypalConfig
@Value("$paypal.client.app")
private String clientId;
@Value("$paypal.client.secret")
private String clientSecret;
@Value("$paypal.mode")
private String mode;
@Bean
public Map<String, String> paypalSdkConfig()
Map<String, String> sdkConfig = new HashMap<>();
sdkConfig.put("mode", mode);
return sdkConfig;

@Bean
public OAuthTokenCredential authTokenCredential()
return new OAuthTokenCredential(clientId, clientSecret, paypalSdkConfig());

@Bean
public APIContext apiContext() throws PayPalRESTException
APIContext apiContext = new APIContext(authTokenCredential().getAccessToken());
apiContext.setConfigurationMap(paypalSdkConfig());
return apiContext;


Tạo enum PaypalPaymentIntent.java trong package com.qlam.config


package com.qlam.config;
public enum PaypalPaymentIntent
sale, authorize, order

Tạo enum PaypalPaymentMethod.java trong package com.qlam.config


package com.qlam.config;
public enum PaypalPaymentMethod
credit_card, paypal

Tạo class Utils.java trong package com.qlam.utils


package com.qlam.util;
import javax.servlet.http.HttpServletRequest;
public class Utils
public static String getBaseURL(HttpServletRequest request)
String scheme = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String contextPath = request.getContextPath();
StringBuffer url = new StringBuffer();
url.append(scheme).append("://").append(serverName);
if ((serverPort != 80) && (serverPort != 443))
url.append(":").append(serverPort);

url.append(contextPath);
if(url.toString().endsWith("/"))
url.append("/");

return url.toString();


Tạo class PaypalService.java trong package com.qlam.service


package com.qlam.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.PaymentExecution;
import com.paypal.api.payments.RedirectUrls;
import com.paypal.api.payments.Transaction;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import com.qlam.config.PaypalPaymentIntent;
import com.qlam.config.PaypalPaymentMethod;
@Service
public class PaypalService
@Autowired
private APIContext apiContext;
public Payment createPayment(
Double total,
String currency,
PaypalPaymentMethod method,
PaypalPaymentIntent intent,
String description,
String cancelUrl,
String successUrl) throws PayPalRESTException
Amount amount = new Amount();
amount.setCurrency(currency);
amount.setTotal(String.format("%.2f", total));
Transaction transaction = new Transaction();
transaction.setDescription(description);
transaction.setAmount(amount);
List<Transaction> transactions = new ArrayList<>();
transactions.add(transaction);
Payer payer = new Payer();
payer.setPaymentMethod(method.toString());
Payment payment = new Payment();
payment.setIntent(intent.toString());
payment.setPayer(payer);
payment.setTransactions(transactions);
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl(cancelUrl);
redirectUrls.setReturnUrl(successUrl);
payment.setRedirectUrls(redirectUrls);
apiContext.setMaskRequestId(true);
return payment.create(apiContext);

public Payment executePayment(String paymentId, String payerId) throws PayPalRESTException
Payment payment = new Payment();
payment.setId(paymentId);
PaymentExecution paymentExecute = new PaymentExecution();
paymentExecute.setPayerId(payerId);
return payment.execute(apiContext, paymentExecute);


Tạo class PaymentController.java trong package com.qlam.controller


package com.qlam.controller;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;
import com.qlam.config.PaypalPaymentIntent;
import com.qlam.config.PaypalPaymentMethod;
import com.qlam.service.PaypalService;
import com.qlam.util.Utils;
@Controller
public class PaymentController
public static final String URL_PAYPAL_SUCCESS = "pay/success";
public static final String URL_PAYPAL_CANCEL = "pay/cancel";
private Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private PaypalService paypalService;
@GetMapping("/")
public String index()
return "index";

@PostMapping("/pay")
public String pay(HttpServletRequest request,@RequestParam("price") double price )
String cancelUrl = Utils.getBaseURL(request) + "/" + URL_PAYPAL_CANCEL;
String successUrl = Utils.getBaseURL(request) + "/" + URL_PAYPAL_SUCCESS;
try
Payment payment = paypalService.createPayment(
price,
"USD",
PaypalPaymentMethod.paypal,
PaypalPaymentIntent.sale,
"payment description",
cancelUrl,
successUrl);
for(Links links : payment.getLinks())
if(links.getRel().equals("approval_url"))
return "redirect:" + links.getHref();


catch (PayPalRESTException e)
log.error(e.getMessage());

return "redirect:/";

@GetMapping(URL_PAYPAL_CANCEL)
public String cancelPay()
return "cancel";

@GetMapping(URL_PAYPAL_SUCCESS)
public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId)
try
Payment payment = paypalService.executePayment(paymentId, payerId);
if(payment.getState().equals("approved"))
return "success";

catch (PayPalRESTException e)
log.error(e.getMessage());

return "redirect:/";


Tạo các file view html với thymeleaf engine


Trong src/main/resourse/templates

Tạo file index.html


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Paypal Payment with Spring Boot - ShareEverythings.com</title>
</head>
<body>
<h1>Paypal Payment with Spring Boot - ShareEverythings.com</h1>
<form method="post" th:action="@/pay">
<input type="text" value="5" name="price" />
<button type="submit"> Payment with Paypal </button>
</form>
</body>
</html>

Tạo file success.html


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Paypal Payment with Spring Boot - ShareEverythings.com</title>
</head>
<body>
<h1>Payment Success !</h1>
<a href="/" >Go Home</a>
</body>
</html>

Taọ file cancel.html


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Paypal Payment with Spring Boot - ShareEverythings.com</title>
</head>
<body>
<h1>Canceled by user</h1>
<a href="/" >Go Home</a>
</body>
</html>

Xong Run APP lên thôi ! Chạy project với Spring Boot App nhé


paypal9


Lưu ý: chúng ta cần tài khoản ảo tức là sandbox để test project này.

Vào sandbox > account bạn sẽ thấy có 2 tài khoản dạng thế này:

xxx-facilitator@xxx : loại tài khoản doanh nghiệp

xxx-buyer@xxx : loại tài khoản cá nhân


paypal10


Bạn nên đổi password trong Profile các tài khoản trên. Ngoài ra trong mục Profile còn nhiều phần khác nữa, bạn hãy tự khám phá nhé!

Xong. Chúng ta test app nào! Bạn hãy nhập số tiền sau đó nhấn Payment With Paypal

Nó sẽ chuyển hướng sang trang đăng nhập vào paypal để thanh toán


paypal11


Lưu ý: đây là trang sandbox.paypal trang này tiền ảo nhé(tiền này không phải của bạn đâu 😀 )


paypal12


Trang xác nhận thanh toán


paypal13


Nếu bạn thanh toán thành công nó sẽ chuyển sang trang success


paypal14


Nếu bạn không muốn thanh toán thì nhấn link cancel phía dưới khung login. Nó sẽ chuyển sang trang cancel


paypal15


Video Hướng dẫn thanh toán Paypal với Spring Boot + Thymeleaf chi tiết:



Tải source code



Xong, thắc mắc gì bạn hãy nhận xét phía dưới!



Học hành, Lập trình, Spring Framework
Java, Lập trình
Xem Tiếp

Cách dùng Statement, PrepareStatement và CallableStatement trong Java

Leave a Comment

JDBC Statement trong java: Statement, PrepareStatement và CallableStatement


So sánh Statement với PreparedStatement và CallableStatement trong JDBC Java

Nếu bạn chưa biết JDBC là gì tham thảo bài viết này trước nhé!
JDBC Statement trong java dùng để làm gì?
jdbc
Khi một kết nối được thiết lập, chúng ta có thể tương tác với cơ sở dữ liệu. JDBC Statement, PreparedStatement và CallableStatement định nghĩa những phương thức và thuộc tính, cho phép chúng ta thực thi câu lệnh SQL và nhận dữ liệu từ cơ sở dữ liệu của bạn, trong đó:


  • Statement  –  Sử dụng để thực hiện các câu truy vấn SQL tĩnh, không có tham số.

  • PreparedStatement – Sử dụng để thực hiện các  câu truy vấn SQL động hoặc có tham số.

  • CallableStatement – Sử dụng để thực thi các stored procedures.

Statement


Statement được sử dụng để thực thi các câu lệnh SQL tĩnh, chúng ta không thể truyền tham số vào câu SQL trong thời gian runtime.

Statement có hiệu năng (performance) kém hơn  PrepareStatement và CallableStatement .

Statement thường được sử dụng trong trường hợp câu lệnh SQL chỉ chạy 1 lần, ví dụ sử dụng để thực thi các câu SQL định nghĩa cơ sở dữ liệu – DDL (Data Denifition Language) như CREATE, ALTER, DROP…

Ví dụ Statement:


String sql = "CREATE TABLE user_info (" +
" id int(11) NOT NULL AUTO_INCREMENT," +
" name varchar(45) DEFAULT NULL," +
" email varchar(100) DEFAULT NULL," +
" address varchar(255) DEFAULT NULL," +
" date_of_birth datetime DEFAULT NULL," +
" PRIMARY KEY (id)" +
")";
Connection con = connectionUtils.getConnection();
Statement stmt = con.createStatement();
stmt.execute(sql);

Lưu ý:


  • boolean execute (String SQL): Trả về giá trị true nếu thực thi thành công câu lệnh SQL; ngược lại sẽ trả về giá trị false. Sử dụng phương thức này để thực thi các câu lệnh SQL DDL như tạo cơ sở dữ liệu, tạo bảng, …

  • int executeUpdate (String SQL): Trả về số dòng bị tác động khi thực thi các câu lệnh như INSERT, UPDATE hoặc DELETE.

  • ResultSet executeQuery (String SQL): Trả về một đối tượng ResultSet khi bạn thực thi câu lệnh SELECT.

PreparedStatement


PreparedStatement được sử dụng để thực thi các câu truy vấn SQL động hoặc có tham số.

PreparedStatement thừa kế từ Statement nhưng nó cho phép truyền các tham số vào câu SQL trong thời gian run time.

PreparedStatement được khuyên sử dụng trong trường hợp câu SQL được sử dụng nhiều lần.

Ví dụ câu lệnh INSERT được dùng lại nhiều lần để insert 1 danh sách user vào database.


List<User> listUser = new ArrayList<User>();
listUser.add(new User(1, "Messi", "Argentina"));
listUser.add(new User(2, "Ronaldo", "Brazil"));
listUser.add(new User(3, "Rooney", "England"));
String sql = "INSERT INTO user_info (id, name, address) VALUES (?, ?, ?);";
PreparedStatement pstmt = con.prepareStatement(sql);
for (User user : listUser)
pstmt.setInt(1, user.getId());
pstmt.setString(2, user.getName());
pstmt.setString(3, user.getAddress());
pstmt.execute();






CallableStatement


CallableStatement được sử dụng để thực thi stored procedures.

CallableStatement được thừa kế từ PreparedStatement và có hiệu năng cao hơn PreparedStatement.

Với CallableStatement, chúng ta có thể truyền 3 loại tham số vào stored procedures là IN (truyền giá trị vào stored procedures), OUT (lấy kết quả trả về từ stored procedures), IN OUT (thực thi cả IN và OUT).






Ví dụ mình tạo một stored procedures thực hiện lấy user theo id:


CREATE PROCEDURE getUserById(IN idUser int)
BEGIN
SELECT * FROM user_info WHERE id = idUser;
END

Bây giờ mình sẽ sử dụng CallableStatement để gọi câu stored procedures bên trên:

Truyền id = 1 vào stored procedures getUserById và trả kết quả về ResultSet


String sql = "CALL getUserById(?);";
CallableStatement cs = con.prepareCall(sql);
cs.setInt(1, 1);
cs.executeQuery();
ResultSet rs = cs.getResultSet();
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));

Xong. Trên đây là Cách dùng Statement, PrepareStatement và CallableStatement trong JDBC Java có ví dụ đơn giản nhất!



Học hành, Lập trình
Java, Lập trình
Xem Tiếp

JDBC là gì ? Tìm hiểu về JDBC trong Java

Leave a Comment

JDBC là gì ? Tìm hiểu về JDBC trong Java và Cách kết nối java với mysql bằng JDBC


JDBC là gì?


jdbc
JDBC (Java Database Connectivity) là một API tiêu chuẩn dùng để kết nối các chương trình viết bởi Java với các loại cơ sở dữ liệu quan hệ (MySQL, MS SQL, Postgre SQL, Oracle, DB2…).

JDBC chỉ là một tập các interface, các định nghĩa, thông báo lỗi, đặc tả chứ không phải là thư viện. Với mỗi hệ quản trị cơ sở dữ liệu ta sẽ có một cài đặt JDBC riêng cho nó, ví dụ JDBC cho MySQL, JDBC cho MS SQL …


Các thành phần của JDBC


DriverManager: Dùng để quản lý danh sách các Driver (database drivers).
Driver: Dùng để liên kết các kết nối tới cơ sở dữ liệu, dùng để liên kết các liên lạc với cơ sở dữ liệu, điều khiển các liên lạc với database.
Connection: Biểu thị kết nối tới cơ sở dữ liệu. Dùng để tạo ra Statement, PreparedStatement và CallableStatement.
Statement, PreparedStatement, CallableStatement: Chứa lệnh SQL gửi tới cơ sở dữ liệu để thực thi.
ResultSet – biểu diễn một tập kết quả trong cơ sở dữ liệu tạo ra bởi việc sử dụng một câu lệnh SQL là SELECT.
SQLException – một lớp xử lý lỗi ngoại lệ chứa các lỗi truy cập cơ sở dữ liệu.


Java kết nối với database dựa trên nguyên tắc nào?


Java sử dụng JDBC để làm việc với các cơ sở dữ liệu.

jdbc


Ví dụ bạn làm việc với cơ sở dữ liệu Oracle từ Java bạn cần phải có Driver (Đó là class điều khiển việc kết nối với loại cơ sở dữ liệu bạn muốn). Trong JDBC API chúng ta có java.sql.Driver, nó chỉ là một interface, và nó có sẵn trong JDK. Như vậy bạn phải download thư viện Driver ứng với loại Database mà bạn mong muốn.
  • Chẳng hạn với Oracle thì class thi hành Interface java.sql.Driver đó là: oracle.jdbc.driver.OracleDriver

java.sql.DriverManager là một class trong JDBC API. Nó làm nhiệm vụ quản lý các Driver.


Code ví dụ Kết nối java với mysql bằng JDBC


Mình sẽ lấy ví dụ ở stackjava. Tạo cơ sở dữ liệu demo-jdbc và table user_info như hình dưới
jdbc-1
Bây giờ mình sẽ viết 1 chương trình Java kết nối tới database demo-jdbc và hiển thị các thông tin của table user_info

Để kết nối với MySQL bằng Java chúng ta cần download jdbc tương ứng cho MySQL

Các bạn có thể download thư viện jdbc cho MySQL tại đây mysql-connector-java-6.0.6.jar

Hoặc sử dụng maven:


<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>


Ở đây mình sử dụng thư viện mysql-connector-java-6.0.6.jar và copy nó vào project

jdbc-2 jdbc-3
jdbc-4
File Demo.java


package stackjava.com.demomysqljdbc.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo
public static void main(String[] args) throws ClassNotFoundException, SQLException
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo-jdbc", "root", "admin1234");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM user_info");
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("Total columns: " + rsmd.getColumnCount());
for (int i = 1; i <= rsmd.getColumnCount(); i++)
System.out.println(
"Column " + i + " [name: " + rsmd.getColumnName(i) + " - type: " + rsmd.getColumnTypeName(i) + "]");

System.out.println("--------------------");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
con.close();


Giải thích chút nhé:


  • Class.forName dùng để chỉ dẫn cho Java biết sẽ kết nối tới loại database nào. Class.forName(“com.mysql.jdbc.Driver”) dùng để kết nối tới database MySQL

  • DriverManager.getConnection(“jdbc:mysql://localhost:3306/demo-jdbc”, “root”, “admin1234”): tạo một connection tới database có url =jdbc:mysql://localhost:3306/demo-jdbc với username = “root” và password  = “admin1234”

  • ResultSetMetaData sẽ đặt meta data cho ResultSet, ở đây ResultSet lấy từ câu SQL “SELECT * FROM user_info” nên nó sẽ gồm tất cả các column trong table user_info. Nếu bạn chuyển câu SQL thành “SELECT id, name FROM user_info” thì ResultSetMetaData sẽ chỉ có 2 column id, name này thôi.

Kết quả:
jdbc-5
Một số lưu ý:


  • Từ bản mysql-connector-java-6.0.6.jar bắt đầu chuyển class com.mysql.jdbc.Driver  sang com.mysql.cj.jdbc.Driver, nếu bạn vẫn dùng class cũ thì nó sẽ thông báo warning chứ không ảnh hưởng gì.

Nên xem: CÁCH DÙNG STATEMENT, PREPARESTATEMENT VÀ CALLABLESTATEMENT TRONG JAVA


Download code ví dụ Kết nối java với mysql bằng JDBC tại đây



Học hành, Lập trình
Java, Lập trình
Xem Tiếp