所使用到的jar 包:

1、创建实体类

public class User {

	private Integer id;
private String name;
private String address;
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
} }

2、配置映射文件

<hibernate-mapping>
<class name="cn.model.User" table="USER" lazy="true">
<id name="id" column="ID">
<generator class="native"></generator>
</id>
<property name="name" column="NAME" type="java.lang.String" />
<property name="address" column="ADDRESS" type="java.lang.String" />
</class>
</hibernate-mapping>

3、配置hiberante.cfg.xml;hibernate.properties 详细 http://blog.csdn.net/oxiaoxio/article/details/49304591

<hibernate-configuration>
<session-factory name="sessionFactory">
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property> <mapping resource="cn/hbm/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

4、测试用例:

public class Conn {

	public void addUser(){
Configuration cfg=new Configuration();
cfg.configure();
ServiceRegistry sr=new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf=cfg.buildSessionFactory(sr); Session s=sf.openSession();
Transaction trans=s.beginTransaction();
User user=new User();
user.setName("汤姆");
user.setAddress("北海");
s.save(user);
trans.commit();
s.close();
}
}

代码优化:

新建一个类名字是HibernateSessionFactory:

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder; public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry; static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
} public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
} public static Configuration getConfiguration() {
return configuration;
} }

优化过以后代码:

public void addUser(){
Session s=HibernateSessionFactory.getSession();
Transaction trans=s.beginTransaction();
User user=new User();
user.setName("汤姆11");
user.setAddress("北海");
s.save(user);
trans.commit();
s.close();
}

最新文章

  1. VMware下centos6.3minimal搭建网络环境
  2. Haar-like特征
  3. Sunny-Code 最终版总结会议
  4. Sublime Text 3 Install Markdown Preview Plugins
  5. hash算法总结收集
  6. AsyncTask异步任务类使用学习
  7. VC MFC在CMFCToolBar工具栏中加入组合框
  8. 解决mysqldump: Got error: 1044: Access denied for user
  9. IIS安装Web Deploy之后没有显示右键菜单
  10. Ado.Net小练习02(小项目CUID
  11. [Locked] Strobogrammatic Number &amp; Strobogrammatic Number II &amp; Strobogrammatic Number III
  12. 转:MVC分页
  13. Android 内部存储相关的函数(getCacheDir,getDir, getFileStreamPath,getFilesDir,openFileInput, ...)
  14. 【Javascript】搞定JS面试——跨域问题
  15. Spring使用@Scheduled定时调度
  16. console输出彩色字体
  17. 我对CopyOnWrite的思考
  18. CSDN博客文章的备份及导出电子书CHM
  19. 2-Eighteenth Scrum Meeting-20151218
  20. ROS学习(五)—— 编译ROS Package

热门文章

  1. python操作 redis-list
  2. SQL Server 连接和事务相关的问题。
  3. create custom launcher icon 细节介绍
  4. logcat错误日志
  5. openssl 加密
  6. Linux(gnu)环境动态链接库的搜索路径
  7. 变形课(dfs)
  8. Android EditText限制输入一些固定字符的属性
  9. Android 开发中的View事件监听机制
  10. C++ extern &quot;C&quot;,C与C++的区别