How to create a Maven project with Hibernate libs?

This blog will be a demo to describe this issue.

Using tools:

1. eclipse

2. maven

Now, we should look at the project structure :

the result at the console :

[INFO] Scanning for projects...
[INFO]
[INFO] Using the builder org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder with a thread count of 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building hibernate-4-maven 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ hibernate-4-maven ---
[INFO] Deleting D:\Development\j2ee\workspace\hibernate-4-maven\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ hibernate-4-maven ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ hibernate-4-maven ---
[INFO] Compiling 2 source files to D:\Development\j2ee\workspace\hibernate-4-maven\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ hibernate-4-maven ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory D:\Development\j2ee\workspace\hibernate-4-maven\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) @ hibernate-4-maven ---
[INFO] Compiling 1 source file to D:\Development\j2ee\workspace\hibernate-4-maven\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ hibernate-4-maven ---
[INFO] Surefire report directory: D:\Development\j2ee\workspace\hibernate-4-maven\target\surefire-reports -------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.b510.hongten.hibernate4maven.TestUser
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate:
select
user0_.id as id0_,
user0_.age as age0_,
user0_.email as email0_,
user0_.gender as gender0_,
user0_.name as name0_
from
tab_user user0_
Id : 1 Name : Hongten Gender : M Age : 18 email : hongtenzone@foxmail.com
Hibernate:
insert
into
tab_user
(age, email, gender, name)
values
(?, ?, ?, ?)
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.298 sec Results : Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 [INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.151 s
[INFO] Finished at: 2014-11-01T23:32:56+08:00
[INFO] Final Memory: 11M/27M
[INFO] ------------------------------------------------------------------------

the result at the database :

==========================================================

// Source Code:

==========================================================

/hibernate-4-maven/src/main/java/com/b510/hongten/hibernate4maven/User.java

/**
*
*/
package com.b510.hongten.hibernate4maven; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table; /**
* @author Hongten
* @created 2014年11月1日
*/
@Entity
@Table(name = "tab_user")
public class User { @Id
@GeneratedValue
private Integer id;
private String name;
@Column(columnDefinition = "int default 0")
private Integer age;
private String gender;
private String email; 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 Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public String getGender() {
return gender;
} public void setGender(String gender) {
this.gender = gender;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
}
}

/hibernate-4-maven/src/main/java/com/b510/hongten/hibernate4maven/util/HibernateUtil.java

/**
*
*/
package com.b510.hongten.hibernate4maven.util; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration; /**
* @author Hongten
* @created 2014年11月1日
*/
public class HibernateUtil { private static final SessionFactory sessionFactory; static {
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
} public static Session getOpenSession() {
return sessionFactory.openSession();
} public static Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}

/hibernate-4-maven/src/test/java/com/b510/hongten/hibernate4maven/TestUser.java

/**
*
*/
package com.b510.hongten.hibernate4maven; import java.util.List;
import java.util.Random; import junit.framework.Assert; import org.hibernate.Query;
import org.hibernate.Session;
import org.junit.Test; import com.b510.hongten.hibernate4maven.util.HibernateUtil; /**
* @author Hongten
* @created 2014年11月1日
*/
public class TestUser { @Test
public void testSave() {
Session session = HibernateUtil.getOpenSession();
session.beginTransaction();
User user = new User();
user.setAge(new Random().nextInt(22));
user.setName("Hongten");
user.setGender("M");
user.setEmail("hongtenzone@foxmail.com"); session.save(user); Assert.assertEquals(true, user.getId() > 0); session.getTransaction().commit();
} @Test
public void testUpdate() {
Session session = HibernateUtil.getOpenSession();
session.beginTransaction();
Query query = session.createQuery("from User");
List<User> list = query.list();
for (User u : list) {
System.out.println("Id : " + u.getId() + " Name : " + u.getName()
+ " Gender : " + u.getGender() + " Age : " + u.getAge()
+ " email : " + u.getEmail());
}
session.getTransaction().commit();
}
}

/hibernate-4-maven/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://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/users
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="current_session_context_class">thread</property>
<property name="hbm2ddl.auto">update</property> <!-- Add POJO to here -->
<mapping class="com.b510.hongten.hibernate4maven.User" /> </session-factory> </hibernate-configuration>

/hibernate-4-maven/src/main/resources/log4j.properties

 log4j.rootLogger=debug,consolelog4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%r  [%t]    %p - %c - %l - %m%n

/hibernate-4-maven/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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.b510.hongten</groupId>
<artifactId>hibernate-4-maven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>hibernate-4-maven</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<!-- Configuration for Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.1-GA</version>
</dependency>
<!-- Configuration for mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.33</version>
</dependency>
<!-- Configuration for log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- Configuration for junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

Source Code Download: http://files.cnblogs.com/hongten/hibernate-4-maven.rar

========================================================

More reading,and english is important.

I'm Hongten

大哥哥大姐姐,觉得有用打赏点哦!多多少少没关系,一分也是对我的支持和鼓励。谢谢。
Hongten博客排名在100名以内。粉丝过千。
Hongten出品,必是精品。

E | hongtenzone@foxmail.com  B | http://www.cnblogs.com/hongten

========================================================

Hibernate4Maven的更多相关文章

随机推荐

  1. 【JAVA集合框架之Set】

    一.Set概述. Set集合的特点是元素不允许重复,而且是无序的(添加和取出的顺序不一致). Set接口中的方法和Collection接口中的方法几乎相同,略. Set接口下常用的两个类:HashSe ...

  2. 无废话ExtJs 入门教程三[窗体:Window组件]

    无废话ExtJs 入门教程三[窗体:Window组件] extjs技术交流,欢迎加群(201926085) 1.代码如下: 1 <!DOCTYPE html PUBLIC "-//W3 ...

  3. Power BI Q&A终于在圣诞前夕盼到

    相信跟所有的数据分析师们一样,赶上年底和年初都是非常忙的时候,即使赶上哪天运气好不加班每天回到家吃完饭恨不得倒在床上就美美的睡上一觉.本人也是如此,正直疲惫之际,尹相志在微博上把我一圈,说Power ...

  4. 攻城狮在路上(叁)Linux(十四)--- 查阅文件内容

    常用命令:cat.tac.nl.more.less.head.tail.od... 一.直接查看文件内容:cat.tac.nl <==一次性全部读取 1.cat [-AbEnTv] 文件名 参数 ...

  5. js判断当前的访问是手机还是电脑

    <script type="text/javascript"> //平台.设备和操作系统 var system ={ win : false, mac : false, ...

  6. 使用PHP获取时间今天 明天 昨天 时间戳的详解

    使用php获取时间今天明天昨天时间戳 2013-06-20 11:12 <?php echo "今天:".date("Y-m-d")."< ...

  7. Spring容器初始化过程

    一.Spring 容器高层视图 Spring 启动时读取应用程序提供的Bean配置信息,并在Spring容器中生成一份相应的Bean配置注册表,然后根据这张注册表实例化Bean,装配号Bean之间的依 ...

  8. HDU 5787 K-wolf Number 数位DP

    K-wolf Number Problem Description   Alice thinks an integer x is a K-wolf number, if every K adjacen ...

  9. barabasilab-networkScience学习笔记6-evolving networks

    第一次接触复杂性科学是在一本叫think complexity的书上,Allen博士很好的讲述了数据结构与复杂性科学,barabasi是一个知名的复杂性网络科学家,barabasilab则是他所主导的 ...

  10. 使用postMesssage()实现跨域iframe页面间的信息传递----转载

    由于web同源策略的限制,当页面使用跨域iframe链接时,主页面与子页面是无法交互的,这对页面间的信息传递造成了不小的麻烦,经过一系列的尝试,最后我发现有以下方法可以实现: 1. 子页面url传参 ...