网络相册开发(4)——Spring中配置JPA

在src/META-INF下添加persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
	version="1.0">
	<persistence-unit name="ApplicationEntityManager"
		transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
	
	</persistence-unit>
</persistence>

 

在Spring的配置文件applicationContext.xml中添加

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
		<property name="url"><value>jdbc:mysql://localhost/sw?createDatabaseIfNotExist=true&amp;useUnicode=true&amp;characterEncoding=utf-8</value></property>
		<property name="username"><value>root</value></property>
		<property name="password"><value>mysql</value></property>
	</bean>
	
	<!-- JPA EntityManagerFactoryBean for EntityManager-->

	<bean id="myEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
            </bean>
        </property>
    </bean>
    
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="myEntityManagerFactory"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>     <tx:annotation-driven transaction-manager="transactionManager"/>

 

这不是唯一一种写法,网络上提供的方法可谓千差万别,我试过大多可用。

建议详读LocalContainerEntityManagerFactoryBean的API文档

 

GenericDaoJpa.java

package net.sw.base.dao.jpa;

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

import javax.persistence.EntityNotFoundException;

import net.sw.base.dao.GenericDao;
import net.sw.base.domain.BaseDomain;
import net.sw.util.PKgen;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;

/**
 * 这个类是所有 DAO 的基类,所有DAO必须继承这个类
 * 
 * 
 * @author vyyv
 * @param <T>  对象类名
 *           
 * @param <PK>  对象主键(ID)的类型
 *            
 */
@Transactional
public class GenericDaoJpa<T extends BaseDomain, PK extends Serializable> extends JpaDaoSupport  implements
		GenericDao<T, PK> {

	/**
	 * 日志文件使用方法 LogFactory.getLog(getClass())
	 * 来源 Commons Logging
	 */
	protected final Log log = LogFactory.getLog(getClass());
	
	private Class<T> persistentClass;

	/**
	 *{@inheritDoc}
	 *
	 */

	public GenericDaoJpa(final Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		return getJpaTemplate().find(
				"from " + this.persistentClass.getName());
	}

	/**
	 * {@inheritDoc}
	 */
	public T get(PK id) {
		T entity = getJpaTemplate().find(this.persistentClass, id);

		if (entity == null) {
			String msg = "Uh oh, '" + this.persistentClass
					+ "' object with id '" + id + "' not found...";
			log.warn(msg);
			throw new EntityNotFoundException(msg);
		}

		return entity;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean exists(PK id) {
		T entity = getJpaTemplate().find(this.persistentClass, id);
		return entity != null;
	}

	/**
	 * {@inheritDoc}
	 */
	
	public T save(T object) {

		if (object.getId()==0) {
			object.setId(PKgen.getInstance(0).nextPK());
			object.setCreatetime(new Date());
			getJpaTemplate().persist(object);
		}else{
			getJpaTemplate().merge(object);
		}
		return object;
	}
	/**
	 * {@inheritDoc}
	 */
	public void remove(PK id) {
		getJpaTemplate().remove(this.get(id));
	}

}

 

注意第88行,一般我们应该在构造方法中添加ID、CreateTime,但是由Flex生成并传递过来的对象不会走Java的构造方法,所以我改在这里添加。

 

AlbumDaoJpa.java

package net.sw.album.dao.jpa;

import java.util.Date;

import net.sw.album.domain.Album;
import net.sw.album.dao.AlbumDao;
import net.sw.base.dao.jpa.GenericDaoJpa;
import net.sw.util.PKgen;

import org.springframework.transaction.annotation.Transactional;

/**
 * 相册数据访问实现
 * 
 * @author vyyv
 * 
 */
//@Repository("albumDao")
@Transactional
public class AlbumDaoJpa extends GenericDaoJpa<Album,Long> implements AlbumDao {

	public AlbumDaoJpa() {
		super(Album.class);
		
	}	
	
}

 

 

@Transactional必须要标注,如果缺少事务,JPA将不能提交数据。

你可能感兴趣的:(DAO,spring,bean,mysql,jpa)