Hibernate CRUD
Hibernate CRUD
小代码2016 发表于2年前
Hibernate CRUD
  • 发表于 2年前
  • 阅读 47
  • 收藏 2
  • 点赞 1
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

摘要: 参考自孔浩

目录结构:

 

代码:

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="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql:///hone</property>

		<!-- 配置 hibernate 的基本信息 -->
		<!-- hibernate 所使用的数据库方言 -->
		<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

		<!-- 执行操作时是否在控制台打印 SQL -->
		<property name="show_sql">true</property>

		<!-- 是否对 SQL 进行格式化 -->
		<property name="format_sql">true</property>

		<!-- 指定自动生成数据表的策略 -->
		<property name="hbm2ddl.auto">update</property>

		<!-- 指定关联的 .hbm.xml 文件 -->
		<mapping resource="com/laolang/domain/Student.hbm.xml" />
	</session-factory>
</hibernate-configuration>

 

com.laolang.domain.Student

package com.laolang.domain;

public class Student {

	public Student() {
		super();
	}

	public Student(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age
				+ ", sex=" + sex + "]";
	}

	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 int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	private int id;
	private String name;
	private int age;
	private String sex;
}

 

com.laolang.student.Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-3-9 8:52:51 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.laolang.domain.Student" table="STUDENT">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="age" type="int">
            <column name="AGE" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="SEX" />
        </property>
    </class>
</hibernate-mapping>

 

com.laolang.util.HibernateUtil

package com.laolang.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

	private final static SessionFactory FACTORY = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		Configuration cfg = new Configuration().configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
				.applySettings(cfg.getProperties()).buildServiceRegistry();
		SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);
		return factory;
	}

	public static SessionFactory getSessionFactory() {
		return FACTORY;
	}

	public static Session openSession() {
		return FACTORY.openSession();
	}

	public static void close(Session session) {
		if (session != null)
			session.close();
	}
}

 

com.laolang.test.TestCrud

package com.laolang.test;

import java.util.List;

import org.hibernate.Session;
import org.junit.Test;

import com.laolang.domain.Student;
import com.laolang.util.HibernateUtil;

public class Testrud {

	@Test
	public void testAdd() {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();

			Student stu = new Student("小代码", 23, "男");

			session.save(stu);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (session != null)
				session.getTransaction().rollback();
		} finally {
			HibernateUtil.close(session);
		}
	}

	@Test
	public void testLoad() {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();
			Student stu = (Student) session.load(Student.class, 3);
			System.out.println(stu);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			HibernateUtil.close(session);
		}
	}

	@Test
	public void testUpdate() {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();

			Student stu = (Student) session.load(Student.class, 3);
			stu.setAge(66);
			session.update(stu);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (session != null)
				session.getTransaction().rollback();
		} finally {
			HibernateUtil.close(session);
		}
	}

	@Test
	public void testDelete() {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();

			Student stu = new Student();
			stu.setId(2);
			session.delete(stu);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (session != null)
				session.getTransaction().rollback();
		} finally {
			HibernateUtil.close(session);
		}
	}

	@SuppressWarnings("unchecked")
	@Test
	public void testList() {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();

			List<Student> stus = session.createQuery("from Student").list();
			for (Student u : stus) {
				System.out.println(u);
			}

			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (session != null)
				session.getTransaction().rollback();
		} finally {
			HibernateUtil.close(session);
		}
	}

	@SuppressWarnings("unchecked")
	@Test
	public void testListPage() {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();

			List<Student> stus = session.createQuery("from Student")
					.setFirstResult(2).setMaxResults(2).list();
			for (Student u : stus) {
				System.out.println(u);
			}

			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (session != null)
				session.getTransaction().rollback();
		} finally {
			HibernateUtil.close(session);
		}
	}

}

 

需要注意的点:

1、主键修改为native

2、如果是mysql5.5,则修改

 <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

也就是多了一个5

 

 

  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 34
博文 311
码字总数 153495
×
小代码2016
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: