利用单例对hibernate进行优化成模板

利用单列来优化代码,实现对数据库数据的插入

首先写一个java映射类:将来这个用来生成一个表

packagecom.fish.hibernate.domain;

public class User {

private int id;

privateString name;

private String address;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

publicString getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

publicString getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

}

2.写一个关联表的xml 利用该类来映射创建一个表

<?xmlversion="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/HibernateMapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping

package="com.fish.hibernate.domain">

<class name="User" >

<id name="id">

<generator class="native"/>

</id>

<property name="name"/>

<property name="address"/>

</class>

</hibernate-mapping>

3.利用配置xml来关联数据库

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/HibernateConfiguration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory >

<property name="connection.driver_class">com.mysql.jdbc.Driver</property>

<property name="connection.url">jdbc:mysql://127.0.0.1:3306/test</property>

<property name="connection.username">root</property>

<property name="connection.password">330127</property>

<property name="hbm2ddl.auto">create</property>//利用类在数据库建表

<propertyname="dialect">org.hibernate.dialect.MySQLDialect</property>

//这个是mysql的方言

<mapping resource="com/fish/hibernate/domain/User.hbm.xml"/>

//对上面的xml进行关联

</session-factory>

</hibernate-configuration>

4.用单例写一个模板类。

packagecom.fish.hibernate.util;

importorg.hibernate.Session;

importorg.hibernate.SessionFactory;

importorg.hibernate.cfg.Configuration;

public class HibernateTools {

private static SessionFactory sessionFactory;

private HibernateTools() {

}//将构造方法初始化私有

static {//在静态域里面加载,(在构造之前)而且只加载一次。

Configuration configuration = new Configuration();

configuration.configure();

sessionFactory = configuration.buildSessionFactory();//使其得到会话工

}

public static SessionFactory getSessionFactory(){

return sessionFactory;

}

public static Session getSession(){

return sessionFactory.openSession();

}

}

4.一个测试类:

packagecom.fish.hibernate.util;

importorg.hibernate.Session;

importorg.hibernate.Transaction;

importcom.fish.hibernate.domain.User;

public class Test {

public static void main(String[] args) {

Session session = null;

Transaction taTransaction = null;

try {

session = HibernateTools.getSession();

User user = new User();

user.setName("中国");

user.setAddress("亚洲");

taTransaction = session.beginTransaction();

session.save(user);

taTransaction.commit();

session.close();

}finally{

if(session!=null){

session.close();

}

}

}

}

以后对数据的添加只要改这个类的user对象就行了。

这个代码以后大家可以当模板使用!!

你可能感兴趣的:(Hibernate)