最近一直想梳理一下hibernate的相关知识,现在趁着有时间先慢慢写,有什么不到之处请大家指出。
关于hibernate的理论知识就不多讲了,主要还是以代码为主,如果想要系统学习hibernate,大家可以参考《Hibernate实战》这本书。
1.首先创建一张表
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8
2.创建t_user对应的po类
package po;
import java.io.Serializable;
public class TUser implements Serializable {
private static final long serialVersionUID = 4919468989314896832L;
private Long id;
//private String id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/*public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.创建TUser类与t_user表的映射文件TUser.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="po.TUser" table="t_user">
<id name="id">
<!-- 主键生成策略 -->
<generator class="identity"/>
<!-- <generator class="uuid"/> -->
</id>
<property name="name"/>
</class>
</hibernate-mapping>
4.使用log4j作为日志
#
# Hibernate, Relational Persistence for Idiomatic Java
#
# License: GNU Lesser General Public License (LGPL), version 2.1 or later.
# See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
#
### direct log messages to stdout ###
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
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
#log4j.logger.org.hibernate=info
log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
5.创建hibernate配置文件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 >
<!-- mysql数据库驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- mysql数据库名称 -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_test</property>
<!-- 数据库的登陆用户名 -->
<property name="hibernate.connection.username">mysql</property>
<!-- 数据库的登陆密码 -->
<property name="hibernate.connection.password">mysql</property>
<!-- 方言:为每一种数据库提供适配器,方便转换 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="po/TUser.hbm.xml"/>
</session-factory>
</hibernate-configuration>
6.测试代码
package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import po.TUser;
public class HibernateTest {
public static void main(String[] args) {
Session session = null;
try {
session = getCurrentSession();
Transaction transaction = session.beginTransaction();// 开启事务
TUser user = new TUser();
user.setName("用户名223");
session.save(user);
transaction.commit(); // 提交事务
}catch(Exception e){
e.printStackTrace();
} finally {
if (session != null) {
if (session.isOpen()) {
session.close();// 关闭session
}
}
}
}
public static Session getCurrentSession(){
Configuration config = new Configuration().configure("conf/hibernate.cfg.xml");
SessionFactory factory = config.buildSessionFactory();
Session session = null;
session = factory.openSession();
return session;
}
}