文档章节

Hibernate CRUD

小代码2016
 小代码2016
发布于 2016/03/09 09:48
字数 672
阅读 55
收藏 2

目录结构:

 

代码:

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

 

 

© 著作权归作者所有

共有 人打赏支持
小代码2016
粉丝 36
博文 328
码字总数 153495
作品 0
安阳
程序员
Hibernate创建SessionFactory是程序卡住不运行?

使用Hibernate4写一个CRUD示例,javase程序,在main方法中创建sessionFactory,使用如下代码: private HibernateUtils() { try { if (this.sessionFactory == null) { Configuration cfg = new......

灰度乌鸦
2014/05/13
474
0
不知道为什么SSH 这么流行

以前曾经用过 SSH 来做程序,有几个感受: Spring: 里面有些不错的最佳实践,这个东西确实比较实用。特别是Spring MVC,加上freemarker非常棒。而且体积很小。 JDBCTemplate 也蛮实用的 Hibe...

宏哥
2010/12/17
8.9K
92
baomidou/mybatisplus-spring-boot-starter

#mybatisplus-spring-boot-starter mybatisplus-spring-boot-starter 为 Mybatis-Plus 快速集成 spring-boot 简化配置而生,不再需拿 MyBatis 和 Hibernate 相比,mybatis-plus 作为 mybati......

baomidou
2017/05/05
0
0
Hibernate Contextual sessions

Hibernate Contextual sessions Contextual sessions:上下文session, 一个session只在一个给点的上下文中有效。 从3.0.1开始,Hibernate添加了SessionFactory.getCurrentSession()方法获取...

LiJIaming
2012/07/01
0
0
A Note on Hibernate - One To Many

Download hibernate-test.zip - 8.4 KB Introduction This is a note on Hibernate one to many mappings. Background This is a note on Hibernate one to many mappings. Before working o......

Dr. Song Li
2017/12/24
0
0

没有更多内容

加载失败,请刷新页面

加载更多

CentOS 7.* 配置网络

配置静态IP 进入配置文件目录 cd /etc/sysconfig/network-scripts 查找以 ifcfg-eno 开头的文件并编辑它 vi ifcfg-ens32 修改文件中的变量值 BOOTPROTO=staticONBOOT=yesIPADDR=192.168...

阿白
54分钟前
1
0
深入理解OAuth2.0协议

1. 引言 如果你开车去酒店赴宴,你经常会苦于找不到停车位而耽误很多时间。是否有好办法可以避免这个问题呢?有的,听说有一些豪车的车主就不担心这个问题。豪车一般配备两种钥匙:主钥匙和泊...

xtof
58分钟前
1
0
Linux学习-0920

3.4 usermod命令 3.5 用户密码管理 3.6 mkpasswd命令 一、usermode命令 usermode作用是用来修改用户信息。 方法: usermod 参数 username 示例1:修改用户uid usermod -u 1010 test5 示例2...

wxy丶
今天
1
0
synchronized锁对象的坑

今天本来写点其他东西,碰巧写了一下synchronized,没想到掉坑里面了,大佬别笑。 起初代码大概是这样的: package com.ripplechan.part_1_2_3;import java.util.concurrent.CountDownL...

RippleChan
今天
1
0
XAMPP环境搭建(Apache + MariaDB + PHP + Perl)

operation system:ubuntu-18.04.1 step1:download XAMPP #sudo wget https://www.apachefriends.org/xampp-files/7.2.9/xampp-linux-x64-7.2.9-0-installer.run step2:install XAMPP #sudo ......

硅谷课堂
今天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部