(六)- 构建Hibernate项目
最后更新于:2022-04-01 20:44:50
前面我们使用Maven构建了Struts2项目,这里我们来试一下Hibernate项目:
ps: 昨天晚上没有整明白,例子也一直有问题,就没有完成博客,早上起来才明白错在哪![大笑](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-01-19_569e21abc5518.gif)
这里的例子,大体框架应该是正确的,但是,对于Maven的很多约定都没有掌握,估计包的命名都不是非常好,等以后,理解深刻了再改吧![微笑](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-01-18_569ca449c5105.gif)
### 1. 构建一个基本的Web项目
这里请参考前面的博客,一样的
### 2. 添加依赖,修改pom.xml
~~~
4.0.0
com.deppon.demo
test03
war
0.0.1-SNAPSHOT
test03 Maven Webapp
http://maven.apache.org
UTF-8
junit
junit
4.10
test
org.hibernate
hibernate-core
3.6.5.Final
log4j
log4j
1.2.16
org.slf4j
slf4j-api
1.6.1
org.slf4j
slf4j-nop
1.6.4
javassist
javassist
3.11.0.GA
test03
~~~
在保存的时候,Maven会自动从库中各种包下载到本地,如果有异常的话,可以尝试手动下载
### 3. 添加hibernate.cfg.xml和log4j.properties资源文件
注意,资源文件的话,根据约定,需要放在src/main/resources文件夹下
hibernate.cfg.xml
~~~
com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc:sqlserver://localhost:1433;DatabaseName=Demo
ygy
shishi
none
org.hibernate.dialect.SQLServerDialect
thread
true
true
update
~~~
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 SESSIONMAP = new ThreadLocal();
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 personList = session.createQuery("select p from PersonEntity p").list();
for(PersonEntity eachPerson : personList) {
System.out.println(eachPerson);
}
session.getTransaction().commit();
HibernateUtil.closeSession();
}
}
~~~
项目结构如下图所示:
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-09-06_57ce64fbf4085.png)
对了,注意一下,在上面的pom.xml中,没有看到数据库驱动包,我用的是SQL Server,直接将jar包放到了项目的lib文件夹下,而从网上查的说,使用scope引入本地的包,试了一下,好像不行,等我再试一试。
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-09-06_57ce64fc1b3d5.png)
### 5. 测试
如果你现在运行JUnit测试的话,是不会成功的,昨天晚上就是这个原因,提示说找不到hibernate.cfg.xml,
后来发现,在target文件夹下,并没有生成class文件,配置文件也没有,这样当然运行不成功
这里需要执行两个命令
使用CMD窗口,进入当前项目的根目录:
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-09-06_57ce64fc3b26a.png)
第一条命令:输入mvn compile
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-09-06_57ce64fc50a58.png)
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-09-06_57ce64fc67e25.png)
注意:这里一定要成功啊,即 BUILD SUCCESS
第二条命令:输入mvn test-compile
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-09-06_57ce64fc7f901.png)
同样的,这里一定要 BUILD SUCCESS
这样的话,再一次运行测试程序,就可以成功了!![大笑](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/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)
';