Hibernate 简单使用(二) JDBC封装

上一篇介绍了Hibernate框架的搭建与简单使用~

这一次就介绍一下Session的封装~

因为Session是线程不安全的,为了保证当前线程只有一个session对象,并且当前线程中的Session不能让其他线程来访问,需要将获取Session的方法进行封装,为了保证Session的线程安全性,需要将Session放到ThreadLocal中。

ThreadLocal为线程本地变量

上一篇Test类中,我贴下代码:

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//1.创建配置对象
		Configuration configuration=new Configuration();
		//2.读取配置对象
		configuration.configure();
		//3.根据配置文件信息创建一级缓存,SessionFactory
		/*
		 * Connection
		 * 映射文件,映射对象
		 * HttpSession 用户与服务器之间的会话
		 * Session  代码与数据库之间的会话
		 */
		SessionFactory ss=configuration.buildSessionFactory();
		//4.创建Session,打开会话
		Session session=ss.openSession();
		//5.开启事务
		Transaction tran=session.beginTransaction();
		session.save(new User(null, "张二", 100.0, new Date()));
		//6.事务的提交
		tran.commit();
		//7.session关闭
		session.close();
		System.out.println("1111111111111111111");
	}
}
有些代码是可以封装起来的~这样就可以使Session线程安全~

如图:

每次session都要开启一个事务,前面的代码就可以封装起来,这样就会减少代码的编写量~

步骤:

1.新建一个类:HibernateSessioFactory

<span style="font-size:14px;">public class HibernateSessioFactory {

	private static SessionFactory sessionFactory;
	//用于存放Session,该对象是线程安全的,只有当前线程才能访问
	private static ThreadLocal<Session>threadLocal;
	static{
		Configuration config=new Configuration();
		config.configure();
		sessionFactory=config.buildSessionFactory();
		threadLocal=new ThreadLocal<Session>();
	}
	public static Session getSession(){
		Session session=threadLocal.get();
		if(session==null||!session.isOpen()){
			session=sessionFactory.openSession();
			threadLocal.set(session);
		}
		return session;
	}
}
</span>
在这个类中通过getSession可以获得session~

这样就封装成功了~注释已经说得很清楚,我就不说了,不懂的话去看我上一篇~

2.写一个简单的例子,来简单使用HibernateSessioFactory,也简单学习一下封装代码的好处。

User类:

public class User implements Serializable{

	private static final long serialVersionUID = 1L;
	Long id;
	String name;
	Double account;
	Date birthday;
	
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(Long id, String name, Double account, Date birthday) {
		super();
		this.id = id;
		this.name = name;
		this.account = account;
		this.birthday = birthday;
	}
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Double getAccount() {
		return account;
	}
	public void setAccount(Double account) {
		this.account = account;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", account=" + account + ", birthday=" + birthday + "]";
	}
	
}
UserDao类:

public class UserDao {

	private Session getSession(){
		return HibernateSessioFactory.getSession();
	}
	public void save(User user){
		Session session=getSession();
		System.out.println("dao:"+session.hashCode());
		session.save(user);
	}
	
	public void deleteByID(long id){
		Session session=getSession();
		User user=(User) session.load(User.class, id);
		session.delete(user);
	}
}
UserService类:

在这个类中写了个register方法~调用了UserDao类中的save方法~

public class UserService {
	
	private UserDao userDao=new UserDao();
	public void register(User user){
		Session session=HibernateSessioFactory.getSession();
		System.out.println("service:"+session.hashCode());
		
		Transaction transaction=session.beginTransaction();//开启事务
		userDao.save(user);//增删改查
		transaction.commit();//事务的提交
		session.close();
	}
}
MainTest类-程序的入口:

public class MainTest {

	public static void main(String[] args) {
		UserService userService=new UserService();
		System.out.println(1111111111);
		userService.register(new User(null, "新添加的", 891.1,new Date()));
	}
}
这里给大家解释一下,如图:





在这里代码已经基本完成了,但是不要忘记配置文件和映射文件啊~

配置文件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>

		<!-- Database connection settings -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://127.0.0.1:3306/ssh</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>

		<!-- SQL dialect -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- Echo all executed SQL to stdout -->
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>

		<!-- Drop and re-create the database schema on startup -->
		<property name="hbm2ddl.auto">update</property>

	     <mapping resource="com/xu/day5/cms/dao/use.hbm.xml" />
		
	</session-factory>

</hibernate-configuration>
映射文件use.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.xu.day5.cms.dao">

	<class name="User" table="tb_user">
		<id name="id" column="id">
			<generator class="increment" />
		</id>
		<property name="name" />
		<property name="account" />
		<property name="birthday" />
	</class>

</hibernate-mapping>

效果图我就不贴了~

有问题的可以和我一起交流~微笑



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值