《Hibernate 系列》- 入门例子

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

分享
跟我学

项目结构



--src/main/java
----com.easy.a_basic
------TestApp.java
------User.java
------hibernate.cfg.xml
------User.hbm.xml
----build.gradle

build.gradle



compile group: 'org.hibernate', name: 'hibernate-core', version: '5.1.0.Final'
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.38'
compile group: 'junit', name: 'junit', version: '4.12'

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




TestApp.java



public class TestApp {
public static void main(String[] args) {
//1.加载配置文件
URL url=TestApp.class.getResource("/com/easy/a_basic/hibernate.cfg.xml");
Configuration conf=new Configuration().configure(url);
//2.创建工厂
SessionFactory sessionFactory = conf.buildSessionFactory();
//3.通过session建立与数据库的关系
Session session = sessionFactory.openSession();
//4.开启事务
Transaction trans=session.beginTransaction();
//5.业务逻辑
User user=new User();
user.setUsername("Kimsime");
user.setAge(18);
session.save(user);
//6.提交事务
trans.commit();
//7.关闭资源
session.close();
sessionFactory.close();
}
}

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台