Spring集成Hibernate

本文详细介绍了如何使用Java的ORM框架与Spring框架进行整合,通过实例展示了如何操作数据库,实现数据持久化,以及如何在Spring框架下进行事务管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码结构和使用的jar

 

Student.java

 

package com.orange.entity;

public class Student {
	private Integer id;
	private String name;
	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;
	}
	
}


Student.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 package="com.orange.entity">
    <class name="Student" table="t_student">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name" length="10" not-null="true"/>
    </class>
</hibernate-mapping>


StudentService.java

package com.orange.service;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.orange.entity.Student;
@Transactional
@Service
public class StudentService {
	@Resource
	private SessionFactory sessionFactory;
	public void save(Student student){
		sessionFactory.getCurrentSession().save(student);
	}
	
	public void update(Student student){
		sessionFactory.getCurrentSession().update(student);
	}
	
	public void delete(Integer id){
		Student student = (Student)sessionFactory.getCurrentSession().get(Student.class, id);
		sessionFactory.getCurrentSession().delete(student);
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)//查询不需要事务
	public Student getStudent(Integer id){
		return(Student)sessionFactory.getCurrentSession().get(Student.class, id);
	}
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)//查询不需要事务
	public List<Student> getAllStudent(){
		return sessionFactory.getCurrentSession().createQuery("from Student").list();
	}
}


MainTest.java

package com.orange.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.orange.entity.Student;
import com.orange.service.StudentService;

public class MainTest {
	public static StudentService studentService ;
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
		
		studentService =(StudentService)applicationContext.getBean("studentService");;
		System.out.println("--------------save-------------");
		save();
		System.out.println("--------------getStudent-------------");
		getStudent();
		System.out.println("--------------update-------------");
		update(1);
		System.out.println("--------------delete-------------");
		delete(10);
		System.out.println("--------------getStudentAll-------------");
		getStudentAll();
	}

	
	public static void save(){
		for(int i=1;i<=10;i++){
			Student student = new Student();
			student.setName("大橙子_"+i);
			studentService.save(student);
		}
	}
	
	public static void update(int id){
		Student student =studentService.getStudent(id);
		student.setName("bigOrange");
		studentService.update(student);
	}
	
	public static void delete(int id){
		studentService.delete(id);
	}
	
	public static void getStudent(){
		Student student = studentService.getStudent(1);
		System.out.println(student.getName());
	}
	
	public static void getStudentAll(){
		List<Student> Students=studentService.getAllStudent();
		System.out.println("共有" + Students.size()+"条数据");
		for(Student s : Students){
			System.out.println(s.getName());
		}
	}
}


beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${driverClassName}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<!--initialSize: 初始化连接-->
		<property name="initialSize" value="5" />
		<!--maxIdle: 最大空闲连接-->
		<property name="maxIdle" value="10" />
		<!--minIdle: 最小空闲连接-->
		<property name="minIdle" value="5" />
		<!--maxActive: 最大连接数量-->
		<property name="maxActive" value="15" />
		<!--removeAbandoned: 是否自动回收超时连接-->
		<property name="removeAbandoned" value="true" />
		<!--removeAbandonedTimeout: 超时时间(以秒数为单位)-->
		<property name="removeAbandonedTimeout" value="180" />
		<!--maxWait: 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒-->
		<property name="maxWait" value="3000" />
		<!-- 用来验证从连接池取出的连接,在将连接返回给调用者之前.如果指定,则查询必须是一个SQL SELECT并且必须返回至少一行记录 -->
		<property name="validationQuery">
			<value>SELECT 1</value>
		</property>
	</bean>
	
	<!-- 配置hibernate sessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingResources">
			<list>
				<value>com/orange/entity/Student.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<value>
				hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
				hibernate.hbm2ddl.auto=create
				hibernate.show_sql=true
				hibernate.format_sql=false
		    </value>
		</property>
	</bean>

	<!-- 指定jdbc属性文件(jdbc.properties)位置 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<!-- 启用注解注入 -->
	<context:annotation-config />
	<!-- 对 com.orange.Service 下的类扫描交给spring管理-->
	<context:component-scan base-package="com.orange.Service"></context:component-scan>
	<!--使用的管理器 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- 使用注解配置spring事务 -->
	<tx:annotation-driven transaction-manager="txManager" />
</beans>


jdbc.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/t2?useUnicode=true&characterEncoding=UTF-8
username=root
password=123456


执行结果

log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
AbandonedObjectPool is used (org.apache.commons.dbcp.AbandonedObjectPool@ebd76a)
   LogAbandoned: false
   RemoveAbandoned: true
   RemoveAbandonedTimeout: 180
--------------save-------------
Hibernate: insert into t_student (name) values (?)
Hibernate: insert into t_student (name) values (?)
Hibernate: insert into t_student (name) values (?)
Hibernate: insert into t_student (name) values (?)
Hibernate: insert into t_student (name) values (?)
Hibernate: insert into t_student (name) values (?)
Hibernate: insert into t_student (name) values (?)
Hibernate: insert into t_student (name) values (?)
Hibernate: insert into t_student (name) values (?)
Hibernate: insert into t_student (name) values (?)
--------------getStudent-------------
Hibernate: select student0_.id as id0_0_, student0_.name as name0_0_ from t_student student0_ where student0_.id=?
大橙子_1
--------------update-------------
Hibernate: select student0_.id as id0_0_, student0_.name as name0_0_ from t_student student0_ where student0_.id=?
Hibernate: update t_student set name=? where id=?
--------------delete-------------
Hibernate: select student0_.id as id0_0_, student0_.name as name0_0_ from t_student student0_ where student0_.id=?
Hibernate: delete from t_student where id=?
--------------getStudentAll-------------
Hibernate: select student0_.id as id0_, student0_.name as name0_ from t_student student0_
共有9条数据
bigOrange
大橙子_2
大橙子_3
大橙子_4
大橙子_5
大橙子_6
大橙子_7
大橙子_8
大橙子_9

 

代码和jar包已上传 http://download.youkuaiyun.com/detail/itjavaer/8179743 ,下载后导入eclipse就能运行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值