💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
前面我们使用Maven构建了Struts2项目,这里我们来试一下Hibernate项目: ps: 昨天晚上没有整明白,例子也一直有问题,就没有完成博客,早上起来才明白错在哪![大笑](https://box.kancloud.cn/2016-01-19_569e21abc5518.gif) 这里的例子,大体框架应该是正确的,但是,对于Maven的很多约定都没有掌握,估计包的命名都不是非常好,等以后,理解深刻了再改吧![微笑](https://box.kancloud.cn/2016-01-18_569ca449c5105.gif) ### 1. 构建一个基本的Web项目 这里请参考前面的博客,一样的 ### 2. 添加依赖,修改pom.xml ~~~ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.deppon.demo</groupId> <artifactId>test03</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>test03 Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 属性配置 --> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <!-- 添加Hibernate依赖 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.5.Final</version> </dependency> <!-- 添加Log4J依赖 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.6.4</version> </dependency> <!-- 添加javassist --> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.11.0.GA</version> </dependency> </dependencies> <build> <finalName>test03</finalName> </build> </project> ~~~ 在保存的时候,Maven会自动从库中各种包下载到本地,如果有异常的话,可以尝试手动下载 ### 3. 添加hibernate.cfg.xml和log4j.properties资源文件 注意,资源文件的话,根据约定,需要放在src/main/resources文件夹下 hibernate.cfg.xml ~~~ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> <property name="connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=Demo</property> <property name="connection.username">ygy</property> <property name="connection.password">shishi</property> <property name="javax.persistence.validation.mode">none</property> <property name="dialect">org.hibernate.dialect.SQLServerDialect</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping class="com.deppon.test03.entity.PersonEntity"/> </session-factory> </hibernate-configuration> ~~~ log4j.properties ~~~ log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.rootLogger=debug, stdout log4j.logger.org.hibernate.tool.hbm2ddl=debug ~~~ ### 4. 新建一个实体类,测试一下 PersonEntity.java ~~~ package com.deppon.test03.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "t_person") public class PersonEntity implements java.io.Serializable { private static final long serialVersionUID = -4376187124011546736L; private Integer id; private String name; @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(length = 50 , nullable = false , unique = true) public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "PersonEntity [id=" + id + ", name=" + name + "]"; } } ~~~ HibernateUtil.java ~~~ package com.deppon.test03.util; import org.apache.log4j.Logger; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { /**ThreadLocal Session Map */ public static final ThreadLocal<Session> SESSIONMAP = new ThreadLocal<Session>(); private static final SessionFactory sessionFactory; private static final Logger LOGGER = Logger.getLogger(HibernateUtil.class); static { try { LOGGER.debug("HibernateUti.static - loading cofig"); sessionFactory = new Configuration().configure("hibernate.cfg.xml") .buildSessionFactory(); LOGGER.debug("HibernateUtil.static - end"); } catch (Throwable ex) { ex.printStackTrace(); LOGGER.error("HibernateUti error : ExceptionInInitializerError"); throw new ExceptionInInitializerError(ex); } } private HibernateUtil() { } public static Session getSession() throws HibernateException { Session session = SESSIONMAP.get(); if(session == null) { session = sessionFactory.openSession(); SESSIONMAP.set(session); } return session; } public static void closeSession() throws HibernateException { Session session = SESSIONMAP.get(); SESSIONMAP.set(null); if(session != null) { session.close(); } } } ~~~ 测试类 ModelTest.java ~~~ package com.deppon.test03.model; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Assert; import org.junit.Test; import com.deppon.test03.entity.PersonEntity; import com.deppon.test03.util.HibernateUtil; public class ModelTest { @Test public void testGetSession() { Session session = HibernateUtil.getSession(); Assert.assertNotNull(session); HibernateUtil.closeSession(); } @Test public void testExport() { new SchemaExport(new Configuration().configure()).create(true , true); } @Test public void testSave() { PersonEntity person = new PersonEntity(); person.setId(100); person.setName("路飞"); Session session = HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); session.save(person); tx.commit(); HibernateUtil.closeSession(); } @Test public void testQuery() { Session session = HibernateUtil.getSession(); session.beginTransaction(); @SuppressWarnings("unchecked") List<PersonEntity> personList = session.createQuery("select p from PersonEntity p").list(); for(PersonEntity eachPerson : personList) { System.out.println(eachPerson); } session.getTransaction().commit(); HibernateUtil.closeSession(); } } ~~~ 项目结构如下图所示: ![](https://box.kancloud.cn/2016-09-06_57ce64fbf4085.png) 对了,注意一下,在上面的pom.xml中,没有看到数据库驱动包,我用的是SQL Server,直接将jar包放到了项目的lib文件夹下,而从网上查的说,使用scope引入本地的包,试了一下,好像不行,等我再试一试。 ![](https://box.kancloud.cn/2016-09-06_57ce64fc1b3d5.png) ### 5. 测试 如果你现在运行JUnit测试的话,是不会成功的,昨天晚上就是这个原因,提示说找不到hibernate.cfg.xml, 后来发现,在target文件夹下,并没有生成class文件,配置文件也没有,这样当然运行不成功 这里需要执行两个命令 使用CMD窗口,进入当前项目的根目录: ![](https://box.kancloud.cn/2016-09-06_57ce64fc3b26a.png) 第一条命令:输入mvn compile ![](https://box.kancloud.cn/2016-09-06_57ce64fc50a58.png) ![](https://box.kancloud.cn/2016-09-06_57ce64fc67e25.png) 注意:这里一定要成功啊,即   BUILD SUCCESS 第二条命令:输入mvn test-compile ![](https://box.kancloud.cn/2016-09-06_57ce64fc7f901.png) 同样的,这里一定要 BUILD SUCCESS 这样的话,再一次运行测试程序,就可以成功了!![大笑](https://box.kancloud.cn/2016-01-19_569e21abc5518.gif) --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - [Maven学习(一)- 环境搭建](http://blog.csdn.net/jolingogo/article/details/8775046) - [Maven学习(二)- 安装m2eclipse插件 ](http://blog.csdn.net/jolingogo/article/details/8796410) - [Maven学习(三)- 使用Maven构建Web项目](http://blog.csdn.net/jolingogo/article/details/8796726) - [Maven学习(四)- 使用Maven构建Web项目-测试](http://blog.csdn.net/jolingogo/article/details/8797153) - [Maven学习(五)- 使用Maven构建Struts2项目](http://blog.csdn.net/jolingogo/article/details/8798052) - [Maven学习(六)- 构建Hibernate项目](http://blog.csdn.net/jolingogo/article/details/8798684) - [Maven学习(七)- 构建Spring项目](http://blog.csdn.net/jolingogo/article/details/8799307) - [Maven学习(八)- 构建MyBatis项目](http://blog.csdn.net/jolingogo/article/details/8801158) - [Maven学习(九)- 构建SSH项目](http://blog.csdn.net/jolingogo/article/details/8811817) - [Maven学习(十) - 阶段小结 ](http://blog.csdn.net/jolingogo/article/details/8821375) - [专栏:Maven学习之旅](http://blog.csdn.net/column/details/yuguiyang-maven.html)