目录结构如图,
1.用MyEclipse建立一个Maven-Java项目,然后给出pom配置,
4.0.0 com.xuebaosoft.hibernate4 hibernate4-maven-conf 0.0.1-SNAPSHOT jar hibernate4-maven-conf http://maven.apache.org UTF-8 junit junit 3.8.1 test org.hibernate hibernate-core 4.2.8.Final org.slf4j slf4j-simple 1.6.1 mysql mysql-connector-java 5.1.6
2.环境准备好以后写一个pojo-UserModel.java,
package modelTest;public class UserModel { private String uuid; private int userId; private String name; private int age; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}
3.配置hibernate数据源环境xml--hibernate.cfg.xml,
com.mysql.jdbc.Driver jdbc:mysql://192.168.191.1:3306/mysql root root org.hibernate.dialect.MySQLDialect true create
解释下:
show_sql为true表示在执行数据库操作的时候sql语句会以log的形式打印在console;
hbm2ddl.auto为create表示先删除指定的实体-关系表(不管存在不存在都先执行删除操作),然后再进行操作,这个也算是hibernate的主要实用优势之一,不用你写sql建表了。
mapping这里对应了实体-关系表的配置文件
4.实体-关系表的配置--UserModel.hbm.xml
解释下,
name为modelTest.UserModel对应的是那个POJO,table为tbl_user表示对应数据库的那个表
id标识userId字段为主键,其余的都不是主键,generator为native或者是increment表示自增,这里有篇帖子希望了解区别的可以参考下:**(帖子我忘了,找个机会补),总之native是本地化的方案,可能会使用increment进行代替,可以理解为native是一个抽象父类,increment是一个实现它的具体类,但具体类不止increment一个,这里自增主键用native和increment都是可以的(官方demo用的就是increment)
这样配置好以后就可以进行测试了。
5.使用JUnit进行测试,
package foo;import junit.framework.Test;import junit.framework.TestCase;import junit.framework.TestSuite;import modelTest.UserModel;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class AppTest extends TestCase { private SessionFactory sessionFactory; public AppTest(String testName) { super(testName); } protected void setUp() throws Exception { sessionFactory = new Configuration().configure().buildSessionFactory(); } protected void tearDown() throws Exception { if (sessionFactory != null) { sessionFactory.close(); } } public static Test suite() { return new TestSuite(AppTest.class); } public void testApp() { UserModel um = new UserModel(); um.setUuid("1"); um.setName("name1"); um.setAge(1); Session s = sessionFactory.openSession(); Transaction t = s.beginTransaction(); s.save(um); t.commit(); }}
6.分析一下,
首先数据库mysql会删除tbl_user这张表,然后重建,之后就是插入一条记录
关键代码也就是
sessionFactory = new Configuration().configure().buildSessionFactory();
然后用这个sessionFactory去open一个session,
Session s = sessionFactory.openSession();
再之后就用这个session利用hibernate操作数据库,就是这么一个过程,
Transaction t = s.beginTransaction();
s.save(um);
t.commit();
其中这个POJO就是让这个session的save使用的,这样就会在ORM的框架下插入一条记录。
文章的意义也就是记录下Hibernate4用的哪些Jar包,还有基本的配置过程。