《Hibernate 系列》- 增删改查

2018-01-11 13:00:08来源:oschina作者:Kimisme人点击

分享
跟我学

项目结构



--src/main/java
----com.easy.b_crud
------HibernateUtils.java
------TestApp.java
------User.java
------hibernate.cfg.xml
------User.hbm.xml

User.java



public class User {
private Integer id;
private String username;
private Integer age;

User.hbm.xml



"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">










hibernate.cfg.xml



"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">


com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/test
root
123456

true
true

update




HibernateUtils.java



public class HibernateUtils {
private static SessionFactory sessionFactory;
static{
URL url=HibernateUtils.class.getClass().getResource("/com/easy/b_crud/hibernate.cfg.xml");
Configuration conf=new Configuration().configure(url);

sessionFactory =conf.buildSessionFactory();

Runtime.getRuntime().addShutdownHook(new Thread(
new Runnable() {
@Override
public void run() {
System.out.println("虚拟机关闭,释放资源");
sessionFactory.close();
}
}));
}

public static Session openSession(){
return sessionFactory.openSession();
}

public static Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
}

测试




public void test_add(){
Session session = HibernateUtils.openSession();
session.beginTransaction();

User user =new User();
user.setUsername("rose");
user.setAge(17);

session.save(user);
session.getTransaction().commit();
session.close();
}


public void test_update(){
Session session = HibernateUtils.openSession();
session.beginTransaction();

User user =new User();
user.setId(1);
user.setUsername("bigJack");
user.setAge(19);

session.update(user);
session.getTransaction().commit();
session.close();
}


public void test_delete(){
Session session = HibernateUtils.openSession();
session.beginTransaction();

User user =new User();
user.setId(2);

session.delete(user);
session.getTransaction().commit();
session.close();
}


public void test_get(){
Session session = HibernateUtils.openSession();
session.beginTransaction();

User user =(User)session.get(User.class, 1);

System.out.println(user);
session.getTransaction().commit();
session.close();
}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台