📄 hibernateexample.java
字号:
package com.myeclipse.hibernate;
import org.hibernate.Transaction;
public class HibernateExample {
/**
* @param args
*/
public static void main(String[] args) {
// 1. Add the new user
addUser();
// 2. Retrieve the user and print it
listUser();
// 3. Change the user record and update it
changeUser();
}
private static void addUser() {
// 1. Create user
User user = new User();
user.setId(1);
user.setUsername("jdoe");
user.setPassword("1234");
user.setFirstName("John");
user.setLastName("Doe");
user.setDateCreated(System.currentTimeMillis());
// 2. Create DAO
UserDAO dao = new UserDAO();
// 3. Start the transaction
Transaction tx = dao.getSession().beginTransaction();
// 4. Add user
dao.save(user);
// 5. Commit the transaction (write to database)
tx.commit();
// 6. Close the session (cleanup connections)
dao.getSession().close();
}
private static void listUser() {
// 1. Create DAO
UserDAO dao = new UserDAO();
// 2. Find user by ID
User user = dao.findById(1);
// 3. Print the user information out
printUser("Printing User, ", user);
// 4. Close the session (cleanup connections)
dao.getSession().close();
}
private static void changeUser() {
// 1. Create DAO
UserDAO dao = new UserDAO();
// 2. Find user by ID
User user = dao.findById(1);
// 3. Change user information
user.setUsername("jsmith");
user.setPassword("abcd");
user.setFirstName("Jane");
user.setLastName("Smith");
// 4. Start the transaction
Transaction tx = dao.getSession().beginTransaction();
// 5. Update the user record with the changes
dao.save(user);
// 6. Commit the transaction (write to database)
tx.commit();
// 7. Load the updated user from the database
User updatedUser = dao.findById(1);
// 8. Print the updated user information out to confirm the changes
printUser("Printing Updated User, ", updatedUser);
// 9. Close the session (cleanup connections)
dao.getSession().close();
}
private static void printUser(String extraText, User user) {
System.out.println(extraText
+ " User[Username: "
+ user.getUsername()
+ ", Password: "
+ user.getPassword()
+ ", First Name: "
+ user.getFirstName()
+ ", Last Name: "
+ user.getLastName() + "]");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -