欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate对数据库进行增删改查

程序员文章站 2022-04-28 19:17:11
...

数据库表结构

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>
        <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hello</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>
        <property name="connection.pool_size">1</property>
        <property name="show_sql">true</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        
        <mapping resource="org/hibernate/entity/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

 User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class name="org.hibernate.entity.User" table="USER">
 
  <id column="id" name="id" >
   <generator class="native"/>
  </id>
  <property name="name" column="name"/>
  <property name="sex" column="sex"/>
  <property name="age" column="age"/>
  <property name="mail" column="mail"/>
  <property name="tel" column="tel"/>
 </class>
</hibernate-mapping>

User实体类

package org.hibernate.entity;

public class User implements java.io.Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1534611458588709655L;
	
	private int id;
	private String name;
	private String sex;
	private int age;
	private String mail;
	private String tel;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getMail() {
		return mail;
	}
	public void setMail(String mail) {
		this.mail = mail;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public User() {
		
	}
	public User(String name,String sex,int age,String mail,String tel) {
		this.name = name;
		this.sex = sex;
		this.age = age;
		this.mail = mail;
		this.tel = tel;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + ", mail=" + mail + ", tel=" + tel
				+ "]";
	}
	
}

 HibernateUtil.java

package org.hibernate.entity;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
	private static SessionFactory sessionFactory;
	private static final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
	static {
		try {
			Configuration cfg = new Configuration().configure();
			sessionFactory = cfg.buildSessionFactory();
		}catch(Throwable ex) {
			throw new ExceptionInInitializerError(ex);
			
		}
	}
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	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 closeSession()throws HibernateException{
		Session session = (Session)threadLocal.get();
		threadLocal.set(null);
		if(session != null) {
			session.close();
		}
	}
	public static void rebuildSessionFactory() {
		try {
			Configuration configuration=new Configuration().configure();
			configuration.configure("/hibernate.cfg.xml");
			sessionFactory = configuration.buildSessionFactory();
		}catch(Exception e) {
			System.err.println("Error Creating SessionFactory");
			e.printStackTrace();
		}
	}
	public static void shutdown() {
		getSessionFactory().close();
	}
}

增删改查(CURD)测试类

注意:HQL语句的 from User where ...中的User表名称是根据书写的映射关系User.hbm.xml文件名中的User决定。

否则报错:(tablename)is not mapped.

package org.hibernate.entity;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;

public class Test {

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@org.junit.Test
	public void test() {
		fail("Not yet implemented");
	}
	
	@org.junit.Test
	public void TestCURD() {
		Session session = HibernateUtil.getSession();
		//开启事务
		session.beginTransaction();
		
		try {
			//增加
			User insertuser = new User("zhangsan","mail",20,"[email protected]","15823455678");
			session.save(insertuser);
			
			//删除
			User deleteuser = (User)session.get(User.class, 10);
			session.delete(deleteuser);
			session.flush();//刷新session
			
			//修改
			User updateuser = (User) session.get(User.class,2);
			updateuser.setMail("[email protected]");
			session.update(updateuser);
			
			//查询
			User queryuser = (User)session.get(User.class,3);
			System.out.println(queryuser.getId()+" "+queryuser.getName()+" "+queryuser.getSex());
				
			//提交事务
			session.getTransaction().commit();
			
		}catch(Exception e) {
			e.printStackTrace();
			//回滚事务
			session.getTransaction().rollback();
		}finally {
			session.close();
		}		
	}

}