hibernate4注解方式配置和XML方式配置差不多
不同之处
1.添加jar包slf4j-simple.jar(太费事,贴图啦)
2.去掉 User.hbm.xml文件
3.实体中添加注解
4.修改hibernate.cfg.xml中的映射文件
5.修改测试文件中SessionFactory的创建方式
详细代码例子
1.实体创建
/hibernate_test/src/com/test/domin/User.java
package com.test.domin;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2.配置文件
/hibernate_test/config/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>
<!-- 数据库驱动名称 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库链接地址 -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<!-- 数据库用户名称 -->
<property name="hibernate.connection.username">root</property>
<!-- 数据库密码 -->
<property name="connection.password">root</property>
<!-- 设置数据库连接池默认个数 -->
<!-- <property name="connection.pool_size">1</property> -->
<!-- 设置数据库SQL语言类型 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">update</property>
<!-- 设置是否显示SQL语句-->
<property name="show_sql">true</property>
<!-- 设置是否格式化SQL语句 -->
<!-- <property name="format_sql">true</property> -->
<!-- 设置使用线程-->
<property name="current_session_context_class">thread</property>
<!-- 设置hibernate的映射文件-->
<mapping class="com.test.domin.User"/>
</session-factory>
</hibernate-configuration>
测试文件
/hibernate_test/test/test/HibernateTest.java
package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.test.domin.User;
public class HibernateTest {
@Test
public void testHibernateEnv() {
Configuration config = new AnnotationConfiguration();
config.configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
User user = new User();
user.setUsername("test2");
user.setPassword("12342");
session.save(user);
System.out.println("保存成功");
session.getTransaction().commit();
}
}
好啦,大功告成,散花庆祝。新手上路,请多多包涵。