之前一直用spring jdbc,觉得是最简洁,最人畜无害的。但是,sql写的我tmd有点烦了,于是今天开始转向hibernate。之前学过一点,但是工作中从来没用过,先大概了解一下近两年来hibernate的发展,其他的也没注意,就是hibernate也支持注解了(可能是我孤陋寡闻了 - -!)也加了对JPA的实现,了解的过程中又发现Spring Data这货。一点点来吧,本文主要是试用一下从基础的Hibernate xml配置,再到annotation,再到与spring集成,再到spring data,再到。。。。。
注:本文不会为你一一讲解怎么配置、怎么用,就是想展示一下代码结构。如果想入门请另google。
完整代码见:http://git.oschina.net/yaolifei/test/tree/master/test-hibernate
-------------------------割割割割割割割割割割割割割-------------------------------------------
User.java
package com.yaolifei.test.user.domain; import java.util.Date; public class User { private Integer id; private String name; private Date birthday; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }UserService.java
package com.yaolifei.test.user.service; import java.util.List; import com.yaolifei.test.user.domain.User; public interface UserService { User getById(Integer id); List<User> getAll(); void save(User user); void update(User user); void remove(User user); }假设没有一点业务逻辑,就纯粹的调用Dao
package com.yaolifei.test.user.service; import java.util.List; import com.yaolifei.test.user.dao.UserDao; import com.yaolifei.test.user.domain.User; public class UserServiceImpl implements UserService { private UserDao userDao; @Override public User getById(Integer id) { return userDao.getById(id); } @Override public List<User> getAll() { return userDao.getAll(); } @Override public void save(User user) { userDao.save(user); } @Override public void update(User user) { userDao.update(user); } @Override public void remove(User user) { userDao.remove(user); } }所以UserDao和UserService差不多是一样的
package com.yaolifei.test.user.dao; import java.util.List; import com.yaolifei.test.user.domain.User; public interface UserDao { User getById(Integer id); List<User> getAll(); void save(User user); void update(User user); void remove(User user); }重点是UserDaoImpl的实现
package com.yaolifei.test.user.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.yaolifei.test.user.domain.User; import com.yaolifei.test.util.HibernateUtil; public class UserDaoImpl implements UserDao { @Override public User getById(Integer id) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); User user = (User) session.get(User.class, id); session.getTransaction().commit(); session.close(); return user; } @Override public List<User> getAll() { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Query query = session.createQuery("from User"); List<User> list = query.list(); session.getTransaction().commit(); session.close(); return list; } @Override public void save(User user) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(user); session.getTransaction().commit(); session.close(); } @Override public void update(User user) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.update(user); session.getTransaction().commit(); session.close(); } @Override public void remove(User user) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.delete(user); session.getTransaction().commit(); session.close(); } }可以看出
SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); // .................. session.getTransaction().commit(); session.close();
这个是模板代码,可以封装下。(不过我相信spring已经做了)
HibernateUtil提供创建单例SessionFactory的方法
HibernateUtil.java
package com.yaolifei.test.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private final static SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); return cfg.buildSessionFactory(); } public static SessionFactory getSessionFactory() { return sessionFactory; } }
下面看下Hibernate的配置:
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/test</property> <property name="connection.username">root</property> <property name="connection.password">880716</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <mapping resource="user.hbm.xml"/> </session-factory> </hibernate-configuration>还有映射文件:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.yaolifei.test.user.domain"> <class name="User" table="SYS_USER"> <id name="id" column="USER_ID"> <generator class="native"/> </id> <property name="name" column="USER_NAME"/> <property name="birthday" type="timestamp" column="USER_BIRTHDAY"/> </class> </hibernate-mapping>测试类
package com.yaolifei.test.user.service; import static org.junit.Assert.*; import java.util.Calendar; import java.util.List; import org.junit.Test; import com.yaolifei.test.user.domain.User; public class UserServiceTest { private UserService userService = new UserServiceImpl(); @Test public void getById() { Integer id = 1; User user = userService.getById(id); assertEquals("yaolifei", user.getName()); } @Test public void getAll() { List<User> user = userService.getAll(); assertEquals(1, user.size()); } @Test public void save() { User user = new User(); user.setName("yaolifei"); Calendar c = Calendar.getInstance(); c.set(1988, 7-1, 16); user.setBirthday(c.getTime()); userService.save(user); } @Test public void update() { User user = userService.getById(1); user.setName("yaolf"); userService.update(user); User newUser = userService.getById(1); assertEquals(newUser.getName(), "yaolf"); } @Test public void remove() { User user = userService.getById(1); userService.remove(user); User newUser = userService.getById(1); assertNull(newUser); } }下面来跑测试
控制台出现一条sql语句: INFO: HHH000232: Schema update complete Hibernate: insert into SYS_USER (USER_NAME, USER_BIRTHDAY) values (?, ?)
因为id是自动生成的,所以没有插入,看下表里的数据:
自动生成了一个sys_user表,看下表结构:
再看下表数据:
下面可以一一测试一下其他代码。这边就不一一贴结果了
测试中。。。。
全部成功。