SpringとHibernateの統合


直接コードでいいから、後で忘れて見るために
 
構成cfg.xmlファイル
<!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.driver_class">com.mysql.jdbc.Driver</property>
		<!--       -->
		<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
		<!--        -->
		<property name="connection.username">root</property>
		<!--       -->
		<property name="connection.password">xiaohu</property>
		<!--       -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!--     sql  -->
		<property name="show_sql">true</property>
		<!--    sql   -->
		<property name="format_sql">true</property>
		<property name="hbm2ddl.auto">update</property>
		
		<mapping resource="com/tenghu/client/model/Log.hbm.xml"/>
		<mapping resource="com/tenghu/client/model/Users.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

エンティティークラスファイルの構成
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.tenghu.client.model">
	
	<class name="Log" table="tab_log">
		<id name="id" column="id">
			<generator class="native"/>
		</id>
		<property name="datetime" column="date_time"/>
		<property name="type" column="type"/>
		<many-to-one name="user" class="Users" column="user_id"/>
	</class>
</hibernate-mapping>

 
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.tenghu.client.model">
	
	<class name="Users" table="tab_user">
		<id name="id" column="id">
			<generator class="native"/>
		</id>
		<property name="name" column="name"/>
		<set name="log" table="tab_log">
			<key column="user_id"/>
			<one-to-many class="Log" />
		</set>
	</class>
</hibernate-mapping>

Spring関連ファイルの構成
<?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: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/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"
			default-autowire="byType">
		<!--   SessionFactory -->
		<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
			<property name="configLocation">
				<value>classpath:hibernate.cfg.xml</value>
			</property>
		</bean>
		<!--         -->
		<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
			<property name="sessionFactory">
				<ref bean="sessionFactory"/>
			</property>
		</bean>
		<!--            -->
		<aop:config>
			<aop:pointcut expression="execution(* com.tenghu.client.dao.impl.*.*(..))" id="allManagerMedel"/>
			<aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMedel"/>
		</aop:config>
		<!--        -->
		<tx:advice id="txAdvice" transaction-manager="transactionManager">
			<tx:attributes>
				<tx:method name="add*" propagation="REQUIRED"/>
				<tx:method name="delete*" propagation="REQUIRED"/>
				<tx:method name="update*" propagation="REQUIRED"/>
				<tx:method name="*" propagation="REQUIRED" read-only="true"/>
			</tx:attributes>
		</tx:advice>
</beans>

 
<?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: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/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"
			default-autowire="byType">
		<!--         -->
		<bean id="userDao" class="com.tenghu.client.dao.impl.UsersDaoImpl">
			<property name="sessionFactory" ref="sessionFactory"/>
			<property name="logDao" ref="logDao"/>
		</bean>
		
		<!--         -->
		<bean id="logDao" class="com.tenghu.client.dao.impl.LogDaoImpl">
			<property name="sessionFactory" ref="sessionFactory"/>
		</bean>
		
		<!--         -->
		<bean id="userService" class="com.tenghu.client.service.impl.UsersServiceImpl">
			<property name="userdao" ref="userDao"/>
		</bean>
</beans>

エンティティークラス
package com.tenghu.client.model;

import java.io.Serializable;
import java.util.Date;

/**
 *      
 * @author xiaohu
 *
 */
public class Log implements Serializable{
	//id
	private int id;
	//    
	private String type;
	//    
	private Date datetime;
	//     
	private Users user;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public Date getDatetime() {
		return datetime;
	}
	public void setDatetime(Date datetime) {
		this.datetime = datetime;
	}

	public Users getUser() {
		return user;
	}
	public void setUser(Users user) {
		this.user = user;
	}
	public Log() {
	}
}

 
package com.tenghu.client.model;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Users implements Serializable{
	//  id
	private int id;
	//   
	private String name;
	//    
	private Set log=new HashSet();
	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 Set getLog() {
		return log;
	}
	public void setLog(Set log) {
		this.log = log;
	}

	public Users(int id, String name) {
		this.id = id;
		this.name = name;
	}
	public Users() {
	}
}

 
dao層
package com.tenghu.client.dao;

import com.tenghu.client.model.Log;

public interface LogDao {
	//    
	public void addLog(Log log);
}

 
package com.tenghu.client.dao.impl;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.tenghu.client.dao.LogDao;
import com.tenghu.client.model.Log;

/**
 *        
 * @author xiaohu
 *
 */
public class LogDaoImpl extends HibernateDaoSupport implements LogDao{

	@Override
	public void addLog(Log log) {
		//    
		this.getHibernateTemplate().save(log);
	}
}

 
package com.tenghu.client.model;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Users implements Serializable{
	//  id
	private int id;
	//   
	private String name;
	//    
	private Set log=new HashSet();
	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 Set getLog() {
		return log;
	}
	public void setLog(Set log) {
		this.log = log;
	}

	public Users(int id, String name) {
		this.id = id;
		this.name = name;
	}
	public Users() {
	}
}

 
package com.tenghu.client.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.tenghu.client.dao.LogDao;
import com.tenghu.client.dao.UsersDao;
import com.tenghu.client.model.Log;
import com.tenghu.client.model.Users;

/**
 *        
 * @author xiaohu
 *
 */
public class UsersDaoImpl extends HibernateDaoSupport implements UsersDao{
	//         
	private LogDao logDao;
	@Override
	public void addUsers(Users user) {
		//    
		this.getHibernateTemplate().save(user);
		//  Log
		Log log=new Log();
		log.setDatetime(new Date());
		log.setType("    -->    ");
		log.setUser(user);
		//      
		logDao.addLog(log);
	}
	public void setLogDao(LogDao logDao) {
		this.logDao = logDao;
	}
	/**
	 *     
	 */
	@Override
	public Users queryUser(Users user) {
		//  Session  
		Session session=this.getSession();
		//  Query  
		Query query=session.createQuery("from Users where name=?");
		//    
		query.setString(0, user.getName());
		//    
		List<Users> list=query.list();
		if(list.size()>0)
			return list.get(0);
		else
			return null;
	}
}

 
サービス層
package com.tenghu.client.service;

import com.tenghu.client.model.Users;

/**
 *         
 * @author xiaohu
 *
 */
public interface UsersService {
	//    
	public void addUsers(Users user);
	//    
	public Users queryUser(Users user);
}

 
package com.tenghu.client.service.impl;

import com.tenghu.client.dao.UsersDao;
import com.tenghu.client.model.Users;
import com.tenghu.client.service.UsersService;

public class UsersServiceImpl implements UsersService{
	//        
	private UsersDao userdao;
	@Override
	public void addUsers(Users user) {
		userdao.addUsers(user);
		throw new RuntimeException();
	}

	@Override
	public Users queryUser(Users user) {
		return userdao.queryUser(user);
	}

	public void setUserdao(UsersDao userdao) {
		this.userdao = userdao;
	}
}

 
テスト
package com.tenghu.client.test;

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

import com.tenghu.client.dao.UsersDao;
import com.tenghu.client.dao.impl.UsersDaoImpl;
import com.tenghu.client.model.Users;
import com.tenghu.client.service.UsersService;

public class Test {
	public static void main(String[] args) {
		//  ApplicationContext  
		ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext-*.xml");
		//       
		UsersService userService=(UsersService) context.getBean("userService");
		//      
		Users user=new Users();
		user.setName("  ");
		
		//    
		Users u=userService.queryUser(user);
		if(null==u){
			userService.addUsers(user);
		}else{
			System.out.println("     ");
		}
	}
}