Hibernate注解式配置 (在Spring中)

1. Spring 配置文件 (主要改变的是SessionFactory的配置)

<?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:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
	http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"
	default-lazy-init="true">
	
	<context:component-scan base-package="cn.javass.h4"></context:component-scan>

	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>

	
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClassName}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="autoCommitOnClose" value="true"/>
		<property name="checkoutTimeout" value="${cpool.checkoutTimeout}"/>
		<property name="initialPoolSize" value="${cpool.minPoolSize}"/>
		<property name="minPoolSize" value="${cpool.minPoolSize}"/>
		<property name="maxPoolSize" value="${cpool.maxPoolSize}"/>
		<property name="maxIdleTime" value="${cpool.maxIdleTime}"/>
		<property name="acquireIncrement" value="${cpool.acquireIncrement}"/>
		<property name="maxIdleTimeExcessConnections" value="${cpool.maxIdleTimeExcessConnections}"/>
	</bean>
<!-- 	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="mappingLocations" value="#{propertyUtils.getList('hibernate.hbm')}"/>	
		<property name="mappingLocations" value="classpath:/cn/javass/h4/hbm/*.hbm.xml"></property>
		<property name="hibernateProperties">
			<value>
			hibernate.dialect=${hibernate.dialect}
			hibernate.show_sql=true
			hibernate.format_sql=false
			hibernate.query.substitutions=true 1, false 0
			hibernate.jdbc.batch_size=20
			hibernate.cache.use_query_cache=false
			</value>
		</property>
		<property name="lobHandler">
			<ref bean="lobHandler" />
		</property>
	</bean> -->

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<!-- 配置Hibernate拦截器,自动填充数据的插入、更新时间 -->
		<!-- <property name="entityInterceptor" ref="entityInterceptor" /> -->
		<property name="dataSource" ref="dataSource" />
		<property name="hibernateProperties">
			<value>
				<!-- 设置数据库方言 -->
				hibernate.dialect=${hibernate.dialect}
				<!-- 设置自动创建|更新|验证数据库表结构 -->
				<!-- hibernate.hbm2ddl.auto=update -->
				<!-- 输出SQL语句到控制台 -->
				hibernate.show_sql=true
				<!-- 格式化输出到控制台的SQL语句 -->
				hibernate.format_sql=false
				<!-- 是否开启二级缓存 -->
				hibernate.cache.use_second_level_cache=false
				<!-- 配置二级缓存产品 -->
				<!-- hibernate.cache.provider_class=org.hibernate.cache.OSCacheProvider -->
				<!-- 是否开启查询缓存 -->
				hibernate.cache.use_query_cache=false
				<!-- 数据库批量查询数 -->
				hibernate.jdbc.fetch_size=50
				<!-- 数据库批量更新数 -->
				hibernate.jdbc.batch_size=30
			</value>
		</property>
		<!-- 方法1:在配置文件中手动注明实体类 -->
<!-- 		<property name="annotatedClasses">
			<list>
				<value>net.entity.User</value>
			</list>
		</property> -->
		<!-- 方法2:自动扫描实体类 -->
		<property name="packagesToScan" value="cn.javass.h4.User.entity"/> 
		
		<property name="lobHandler">
			<ref bean="lobHandler" />
		</property>
	</bean> 
	
	<bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" lazy-init="true"/>


	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<context:annotation-config/>
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
2.  UserEntity 实体代码:

package cn.javass.h4.User.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import static javax.persistence.GenerationType.AUTO;


@Entity
@Table(name = "tbl_user") 
public class UserEntity {
	
    @Id
    @GeneratedValue(strategy=AUTO) 
    @Column(name = "uuid", unique = true, nullable = false)
	private int uuid;
	@Column
    private String userId;
	@Column
	private String name;
	@Column
	private int age;
	
	public int getUuid() {
		return uuid;
	}
	public void setUuid(int uuid) {
		this.uuid = uuid;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	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;
	}

	
}

3. 根据ID 查询UserEntity (简化版, 实际项目中要分成service和dao两个层来完成这一动作)

@Service
Class UserService {
	@Resource(name="sessionFactory")
	private SessionFactory sf;

	@Transactional
	public<T> T getEntityById(Class<T> entityClass, Integer id) {
		Session s= sf.getCurrentSession();
		T entity = s.get(entityClass, id);
		return entity;
	}

}


4. 测试代码 (使用Junit)

public class UserServiceTest {
	private static UserService us;


	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		ApplicationContext ac = new ClassPathXmlApplicationContext("application-context.xml");
		us = ac.getBean(UserService.class);
	}
	@Test
	public void testGetUserEntityById() {
		UserEntity ue = us.getEntityById(UserEntity.class, 1);
		System.out.println(ue.getAge());
	}
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值