Maven+Hibernate4注解0配置示例

时间:2021-04-22 20:34:32

工程使用Maven来 管理依赖,Hibernate版本4.2.0.Final。

工程结构图:

Maven+Hibernate4注解0配置示例

pom.xml文件:

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3 <modelVersion>4.0.0</modelVersion>
4
5 <groupId>com.purple_river.itat.maven.demo.user.dao</groupId>
6 <artifactId>user-dao</artifactId>
7 <version>0.0.1-SNAPSHOT</version>
8 <packaging>jar</packaging>
9
10 <name>user-dao</name>
11 <url>http://maven.apache.org</url>
12
13 <properties>
14 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15 </properties>
16
17 <dependencies>
18 <dependency>
19 <groupId>junit</groupId>
20 <artifactId>junit</artifactId>
21 <version>4.10</version>
22 <scope>test</scope>
23 </dependency>
24 <dependency>
25 <groupId>org.hibernate</groupId>
26 <artifactId>hibernate-core</artifactId>
27 <version>4.2.0.Final</version>
28 </dependency>
29 <dependency>
30 <groupId>mysql</groupId>
31 <artifactId>mysql-connector-java</artifactId>
32 <version>5.1.27</version>
33 </dependency>
34 </dependencies>
35 </project>

 

hibernate.cfg.xml文件:

 1 <?xml version="1.0" encoding="UTF-8"?>  
2 <!DOCTYPE hibernate-configuration PUBLIC
3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
5 <hibernate-configuration>
6 <session-factory>
7 <!--显示执行的SQL语句 -->
8 <property name="show_sql">true</property>
9 <!-- 格式化输出 -->
10 <property name="format_sql">true</property>
11 <!--连接字符串 -->
12 <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
13 <!--连接数据库的用户名 -->
14 <property name="connection.username">root</property>
15 <!--数据库用户密码 -->
16 <property name="connection.password">soft</property>
17 <!--数据库驱动 -->
18 <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
19 <!--选择使用的方言 -->
20 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
21 <property name="hibernate.hbm2ddl.auto">update</property>
22 <property name="configurationClass">org.hibernate.cfg.AnnotationConfiguration</property>
23 <mapping class="com.purple_river.itat.maven.demo.bean.user.User" />
24 </session-factory>
25 </hibernate-configuration>

 

User类:

  1 package com.purple_river.itat.maven.demo.bean.user;
2
3 import java.io.Serializable;
4 import java.util.Date;
5
6 import javax.persistence.Column;
7 import javax.persistence.Entity;
8 import javax.persistence.GeneratedValue;
9 import javax.persistence.Id;
10 import javax.persistence.Table;
11
12 import org.hibernate.annotations.GenericGenerator;
13
14 @Entity
15 @Table(name="user")
16 public class User implements Serializable
17 {
18 private static final long serialVersionUID = -2602075959996355784L;
19 @Id
20 @GenericGenerator(name="generator",strategy="increment")
21 @GeneratedValue(generator="generator")
22 @Column(name="id",nullable=false,unique=true)
23 private long id;
24 /**
25 * @return the id
26 */
27 public long getId() {
28 return id;
29 }
30
31 /**
32 * @param id the id to set
33 */
34 public void setId(long id) {
35 this.id = id;
36 }
37
38 @Column(name="username",nullable=false)
39 private String username;
40 @Column(name="age")
41 private int age;
42 @Column(name="birthday")
43 private Date birthday;
44
45 /**
46 * @return the username
47 */
48 public String getUsername() {
49 return username;
50 }
51
52 /**
53 * @param username the username to set
54 */
55 public void setUsername(String username) {
56 this.username = username;
57 }
58
59 /**
60 * @return the age
61 */
62 public int getAge() {
63 return age;
64 }
65
66 /**
67 * @param age the age to set
68 */
69 public void setAge(int age) {
70 this.age = age;
71 }
72
73 /**
74 * @return the birthday
75 */
76 public Date getBirthday() {
77 return birthday;
78 }
79
80 /**
81 * @param birthday the birthday to set
82 */
83 public void setBirthday(Date birthday) {
84 this.birthday = birthday;
85 }
86
87 /**
88 *
89 */
90 public User() {
91 super();
92 // TODO Auto-generated constructor stub
93 }
94
95 /**
96 * @param username
97 * @param age
98 * @param birthday
99 */
100 public User(String username, int age, Date birthday) {
101 super();
102 this.username = username;
103 this.age = age;
104 this.birthday = birthday;
105 }
106
107 /* (non-Javadoc)
108 * @see java.lang.Object#toString()
109 */
110 @Override
111 public String toString() {
112 return "User [username=" + username + ", age=" + age + ", birthday="
113 + birthday + "]";
114 }
115
116
117 }

 

 

 HibernateUtil类:

 1 /*
2 * @packageName:com.purple_river.itat.maven.demo.user.dao.util
3 * @fileName:HibernateUtil.java
4 * @description:Hibernate操作工具类
5 * @author:luckystar2010
6 * @date:2013-11-28
7 */
8 package com.purple_river.itat.maven.demo.user.dao.util;
9
10 import org.hibernate.SessionFactory;
11 import org.hibernate.cfg.Configuration;
12 import org.hibernate.service.ServiceRegistry;
13 import org.hibernate.service.ServiceRegistryBuilder;
14
15 public final class HibernateUtil {
16 private static SessionFactory factory = null;
17
18 public static SessionFactory getSessionFactory() {
19 if (factory == null) {
20 Configuration conf = new Configuration().configure();
21 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
22 factory = conf.buildSessionFactory(serviceRegistry);
23 }
24
25 return factory;
26 }
27
28 /*public static void main(String[] args) {
29 SessionFactory sf = HibernateUtil.getSessionFactory();
30 System.out.println(sf.toString());
31 }*/
32 }

 

 IUserDao类 :

 1 /*
2 * @packageName:com.purple_river.itat.maven.demo.user.dao
3 * @fileName:IUserDao.java
4 * @description:用户管理数据库操作接口
5 * @author:luckystar2010
6 * @date:2013-11-28
7 */
8 package com.purple_river.itat.maven.demo.user.dao;
9
10 import java.util.List;
11
12 import com.purple_river.itat.maven.demo.bean.user.User;
13
14 public interface IUserDao {
15
16 public void addUser(User user);
17 public User getUser(String name);
18 public List<User> getAll();
19 }

 

 UserDao类:

 1 /*
2 * @packageName:com.purple_river.itat.maven.demo.user.dao
3 * @fileName:UserDao.java
4 * @description:用户管理数据库操作接口
5 * @author:luckystar2010
6 * @date:2013-11-28
7 */
8 package com.purple_river.itat.maven.demo.user.dao;
9
10 import java.util.List;
11
12 import org.hibernate.HibernateException;
13 import org.hibernate.Session;
14 import org.hibernate.SessionFactory;
15
16 import com.purple_river.itat.maven.demo.bean.user.User;
17 import com.purple_river.itat.maven.demo.user.dao.util.HibernateUtil;
18
19 public class UserDao implements IUserDao {
20
21 /* (non-Javadoc)
22 * @see com.purple_river.itat.maven.demo.user.dao.IUserDao#addUser(com.purple_river.itat.maven.demo.bean.user.User)
23 */
24 public void addUser(User user) {
25 if (user == null) {
26 throw new NullPointerException("the entity[user] which to be saved is null!");
27 }
28
29 Session session = null;
30 try {
31 SessionFactory factory = HibernateUtil.getSessionFactory();
32 session = factory.openSession();
33 session.beginTransaction();
34 session.save(user);
35 session.getTransaction().commit();
36 } catch (HibernateException e) {
37 session.getTransaction().rollback();
38 e.printStackTrace();
39 } finally {
40 if (session != null) {
41 session.close();
42 }
43 }
44
45 }
46
47 /* (non-Javadoc)
48 * @see com.purple_river.itat.maven.demo.user.dao.IUserDao#getUser(java.lang.String)
49 */
50 public User getUser(String name) {
51 User user = null;
52 Session session = null;
53 try {
54 SessionFactory factory = HibernateUtil.getSessionFactory();
55 session = factory.openSession();
56 user = (User) session.createQuery("from User where username = ?").setParameter(0, name).uniqueResult();
57 } catch (HibernateException e) {
58 e.printStackTrace();
59 } finally {
60 if (session != null) {
61 session.close();
62 }
63 }
64
65 return user;
66 }
67
68 /* (non-Javadoc)
69 * @see com.purple_river.itat.maven.demo.user.dao.IUserDao#getAll()
70 */
71 public List<User> getAll() {
72 List<User> list = null;
73 try {
74 list = HibernateUtil.getSessionFactory().openSession().createCriteria(User.class).list();
75 } catch (HibernateException e) {
76 // TODO Auto-generated catch block
77 e.printStackTrace();
78 }
79 return list;
80 }
81
82 }

 

 TestUserDao类:

 1 /*
2 * @packageName:com.purple_river.itat.maven.demo.user.dao
3 * @fileName:TestUserDao.java
4 * @description:Test Case for UserDao
5 * @author:luckystar2010
6 * @date:2013-11-28
7 */
8 package com.purple_river.itat.maven.demo.user.dao;
9
10 import java.util.Calendar;
11 import java.util.List;
12
13 import org.jboss.logging.Logger;
14 import org.junit.After;
15 import org.junit.Assert;
16 import org.junit.Before;
17 import org.junit.Test;
18
19 import com.purple_river.itat.maven.demo.bean.user.User;
20
21 public class TestUserDao {
22 public final static org.jboss.logging.Logger logger = Logger.getLogger(TestUserDao.class);
23
24 private IUserDao userDao ;
25
26 @Before
27 public void setUp() {
28 userDao = new UserDao();
29 }
30
31 @Test
32 public void testAddUser() {
33 logger.info("Test [UserDao.addUser].");
34 Calendar c = Calendar.getInstance();
35 c.set(2012, 01,01);
36 User user = new User("admin",1,c.getTime());
37
38 userDao.addUser(user);
39 }
40
41 @Test
42 public void testGetUser() {
43 logger.info("Test [UserDao.getUser].");
44
45 User user = userDao.getUser("admin");
46 logger.info(user);
47 Assert.assertEquals(user.getUsername(),"admin");
48 Assert.assertEquals(user.getAge(),1);
49 }
50
51 @Test
52 public void testGetAll() {
53 logger.info("Test [UserDao.listAll].");
54
55 List<User> userList = userDao.getAll();
56 Assert.assertTrue(userList.size() == 1);
57 logger.info(userList.get(0));
58 }
59
60 @After
61 public void tearDown() {
62 userDao = null;
63 }
64 }

 

 之所以记录下来,是因为搭建环境时遇到了一些错误,所以这里记录对以后有个参考。

下载地址:http://files.cnblogs.com/luckystar2010/user-dao.rar