Hibernate样例工程---Java Annotation
Jdbc编程中,使用Dao层insert、update、delete、select等于数据库交互,在Hibernate中根据简单的Java对象(pojo)与实体类的映射配置自动生成sql语句,是动态生成的。下面是个简单的例子,工程使用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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yeetrack</groupId>
<artifactId>hibernate</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>hibernate Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.24</version>
</dependency>
</dependencies>
<build>
<finalName>hibernate</finalName>
</build>
</project>
实体类(Entity)是与数据库有映射关系的Java类,这个Java类的所有属性都要有getter
和setter
方法,下面的Cat类就是一个实体类。实体类还要配置表名(@Table)、主键(@id)、普通属性(@Column),Cat.java对应代码如下:
package com.yeetrack.hibernate;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Table;
/**
*
* @author youthflies
* @Entity 表示该类能够被Hibernate持久化
* @Table 指定该Entity指定数据库表名
* @id 指定主键
* @Column 指定属性对应的数据表的列名
*
*/
@Entity
@Table(name = "tb_cat")
public class Cat
{
@Id
@GeneratedValue (strategy = GenerationType.AUTO) //指定自增长,sql语句auto_increment
private Integer id;
@Column(name = "name")
private String name;
@Column(name="description")
private String description;
@ManyToOne
@JoinColumn(name = "mother_id") //指定实体类之间的关系,这里一个cat mother可以有多个cat
private Cat mother;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="createDate")
private Date createDate;
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 String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public Cat getMother()
{
return mother;
}
public void setMother(Cat mother)
{
this.mother = mother;
}
public Date getCreateDate()
{
return createDate;
}
public void setCreateDate(Date createDate)
{
this.createDate = createDate;
}
}
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>
<!-- jdbc配置 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/test?CharactorEncoding=utf-8</property>
<property name="connection.username">root</property>
<property name="connection.password">toor</property>
<!-- 使用mysql数据库格式的sql语句 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<!-- 指定Hibernate启动时自动创建表结构 -->
<property name="hbm2ddl.auto">create</property>
<!-- 为每个线程生成一个session -->
<property name="current_session_context_class">thread</property>
<!-- 指定Cat类为Hibernate实体类 -->
<mapping class="com.yeetrack.hibernate.Cat"></mapping>
</session-factory>
</hibernate-configuration>
<mapping class=""
告诉Hibernate,Cat是个实体类,Hibernate将管理Cat与对应的数据库表。
Hibernate工具类,HibernageUtil.java,代码如下:
package com.yeetrack.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
/**
*
* @author youthflies
*
*/
@SuppressWarnings("deprecation")
public class HibernateUtil
{
private static final SessionFactory sessionFactory;
static
{
sessionFactory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
Hibernate使用log4j来输出日志,这里配置一下,在classpath中新建log4j.properties, 内容如下:
### 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= %5p %c{1}:%L - %m%n
#设置日记级别为info,输出到控制台
log4j.rootLogger=info, stdout
### 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
Hibernate是ORM框架,它保存数据时,先通过HibernateSessionUtil的SessionFactory开启一个session会话,然后开启一个Transaction(事务),再执行保存代码,最后提交事务、关闭session。下面是简单的测试代码(CatTest.java):
package com.yeetrack.hibernate;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class CatTest
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
Cat mother = new Cat();
mother.setName("mother cat's name");
mother.setDescription("The Mama cat");
mother.setCreateDate(new Date());
Cat kitty = new Cat();
kitty.setMother(mother);
kitty.setName("kitty");
kitty.setDescription("The baby cat");
kitty.setCreateDate(new Date());
Cat mimmy = new Cat();
mimmy.setMother(mother);
mimmy.setName("mimmy");
mimmy.setDescription("The baby cat");
mimmy.setCreateDate(new Date());
Session session = HibernateUtil.getSessionFactory().openSession(); //打开Hibernate 对话
Transaction trans = session.beginTransaction(); //打开一个事务
//保存Cat
session.persist(mother);
session.persist(kitty);
session.persist(mimmy);
//利用Hibernate createQuery 查询数据库tb_cat表中的所有数据
List<Cat> catList = session.createQuery(" from Cat ").list();
StringBuffer result = new StringBuffer();
result.append("数据库中的数据:n");
for(Cat cc : catList)
{
result.append("Cat baby:"+cc.getName()+", ");
result.append("cat mother:"+(cc.getMother() == null ? "没有记录" : cc.getMother().getName()));
result.append("rn");
}
trans.commit();
session.close();
System.out.println(result.toString());
}
}
运行结果:
INFO Version:37 - HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
INFO Version:41 - HHH000412: Hibernate Core {4.2.0.Final}
INFO Environment:239 - HHH000206: hibernate.properties not found
INFO Environment:342 - HHH000021: Bytecode provider name : javassist
INFO Configuration:1933 - HHH000043: Configuring from resource: hibernate.cfg.xml
INFO Configuration:1952 - HHH000040: Configuration resource: hibernate.cfg.xml
WARN DTDEntityResolver:74 - HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
INFO Configuration:2074 - HHH000041: Configured SessionFactory: null
INFO DriverManagerConnectionProviderImpl:98 - HHH000402: Using Hibernate built-in connection pool (not for production use!)
INFO DriverManagerConnectionProviderImpl:134 - HHH000115: Hibernate connection pool size: 20
INFO DriverManagerConnectionProviderImpl:137 - HHH000006: Autocommit mode: false
INFO DriverManagerConnectionProviderImpl:151 - HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://127.0.0.1:3306/test?CharactorEncoding=utf-8]
INFO DriverManagerConnectionProviderImpl:156 - HHH000046: Connection properties: {user=root, password=****}
INFO Dialect:128 - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
INFO TransactionFactoryInitiator:68 - HHH000399: Using default transaction strategy (direct JDBC transactions)
INFO ASTQueryTranslatorFactory:48 - HHH000397: Using ASTQueryTranslatorFactory
INFO SchemaExport:343 - HHH000227: Running hbm2ddl schema export
DEBUG SchemaExport:353 - Import file not found: /import.sql
DEBUG SQL:104 - alter table tb_cat drop foreign key FKCB83D685D794462
Hibernate: alter table tb_cat drop foreign key FKCB83D685D794462
DEBUG SQL:104 - drop table if exists tb_cat
Hibernate: drop table if exists tb_cat
DEBUG SQL:104 - create table tb_cat (id integer not null auto_increment, createDate datetime, description varchar(255), name varchar(255), mother_id integer, primary key (id))
Hibernate: create table tb_cat (id integer not null auto_increment, createDate datetime, description varchar(255), name varchar(255), mother_id integer, primary key (id))
DEBUG SQL:104 - alter table tb_cat add index FKCB83D685D794462 (mother_id), add constraint FKCB83D685D794462 foreign key (mother_id) references tb_cat (id)
Hibernate: alter table tb_cat add index FKCB83D685D794462 (mother_id), add constraint FKCB83D685D794462 foreign key (mother_id) references tb_cat (id)
INFO SchemaExport:405 - HHH000230: Schema export complete
DEBUG SQL:104 - insert into tb_cat (createDate, description, mother_id, name) values (?, ?, ?, ?)
Hibernate: insert into tb_cat (createDate, description, mother_id, name) values (?, ?, ?, ?)
DEBUG SQL:104 - insert into tb_cat (createDate, description, mother_id, name) values (?, ?, ?, ?)
Hibernate: insert into tb_cat (createDate, description, mother_id, name) values (?, ?, ?, ?)
DEBUG SQL:104 - insert into tb_cat (createDate, description, mother_id, name) values (?, ?, ?, ?)
Hibernate: insert into tb_cat (createDate, description, mother_id, name) values (?, ?, ?, ?)
DEBUG SQL:104 - select cat0_.id as id1_0_, cat0_.createDate as createDa2_0_, cat0_.description as descript3_0_, cat0_.mother_id as mother5_0_, cat0_.name as name4_0_ from tb_cat cat0_
Hibernate: select cat0_.id as id1_0_, cat0_.createDate as createDa2_0_, cat0_.description as descript3_0_, cat0_.mother_id as mother5_0_, cat0_.name as name4_0_ from tb_cat cat0_
数据库中的数据:
Cat baby:mother cat's name, cat mother:没有记录
Cat baby:kitty, cat mother:mother cat's name
Cat baby:mimmy, cat mother:mother cat's name
版权声明
本站文章、图片、视频等(除转载外),均采用知识共享署名 4.0 国际许可协议(CC BY-NC-SA 4.0),转载请注明出处、非商业性使用、并且以相同协议共享。
© 空空博客,本文链接:https://www.yeetrack.com/?p=8
近期评论