'guice', 'warp' ,'domain driven design'

guice -- dependent injection
warp  -- dynamic finder


AbsEntity ---- 抽象类 提炼所有域对象的Generic属性和行为
IEntity   ---- 对象行为的Generic接口

觉得Annotation用的舒服啊. MainModule.java替代Spring的applicationContext.xml配置文件

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

import javax.persistence.EntityManager;

import com.wideplay.warp.persist.Transactional;

/**
 * <p>
 * Entity interface implemented by all persistent classes.
 */
public interface IEntity<T, PK extends Serializable>
{
	public void setEmp(com.google.inject.Provider<EntityManager> emp);

	public String getId();

	public Date getCreatedAt();

	public void setCreatedAt(Date createAt);

	public Date getChangedAt();

	public void setChangedAt(Date changedAt);

	public List<String> validate();

	public T find(PK id);

	public List<T> findAll();

	@Transactional
	public T save(T object);

	@Transactional
	public void remove(PK id);

}


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

import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import com.google.inject.Inject;
import com.wideplay.warp.persist.Transactional;

/**
 * 
 * <p>
 *  This class provides the basic properties for entities (id, createdAt, and
 *  changedAt) as well as default save, remove, find, and findAll methods.
 * 
 * <p>
 *  Custom finders and custom save / remove logic can be implemented in child
 *  entity classes as necessary.
 */
@MappedSuperclass
public abstract class AbsEntity<T, PK extends Serializable> implements IEntity<T, PK>
{

	@Transient
	@Inject
	protected com.google.inject.Provider<EntityManager> emp;

	@Transient
	private Class<T> persistentClass;
	
	@Id
	@Column(length = 36, nullable = false)
	//@GeneratedValue(strategy = GenerationType.AUTO)
	@GeneratedValue(generator = "hibernate-uuid.hex")
	@org.hibernate.annotations.GenericGenerator(name = "hibernate-uuid.hex", strategy = "uuid.hex")
	protected String id;
	

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "created_at", nullable = false)
	protected Date createdAt = new Date();

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "changed_at", nullable = false)
	protected Date changedAt = new Date();

	/**
	 * Constructor for dependency injection.
	 * 
	 * @param persistentClass
	 *            the class type you'd like to persist.
	 */
	public AbsEntity(Class<T> persistentClass)
	{
		this.persistentClass = persistentClass;
	}

	public void setEmp(com.google.inject.Provider<EntityManager> emp) {
		this.emp = emp;
	}

	public String getId() 
	{
		return id;
	}

	public Date getCreatedAt()
	{
		return createdAt;
	}

	public void setCreatedAt(Date createdAt)
	{
		this.createdAt = createdAt;
	}

	public Date getChangedAt() 
	{
		return changedAt;
	}

	public void setChangedAt(Date changedAt) 
	{
		this.changedAt = changedAt;
	}

	public List<String> validate() 
	{
		// create our list for errors
		List<String> errors = new ArrayList<String>();

		// Validate the model fields.
		if (this.id == null || this.id.length() == 0) 
		{
			errors.add("Identifier is null or empty.");
		}
		if (this.createdAt == null)
		{
			errors.add("Created at date is null.");
		}
		// if no errors occured we'll return null.
		if (errors.size() == 0)
		{
			errors = null;
		}

		// return errors that occured
		return errors;
	}

	public T find(PK id)
	{
		return emp.get().find(this.persistentClass, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll()
	{
		return emp.get().createQuery(
				"FROM " + this.persistentClass.getSimpleName()).getResultList();
	}


	@Transactional
	public T save(T object) 
	{
		return emp.get().merge(object);
	}


	@Transactional
	public void remove(PK id) 
	{
		EntityManager em = emp.get();
		em.remove(em.find(this.persistentClass, id));
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean equals(Object o)
	{
		if (this == o)
			return true;
		if (o == null || !(o instanceof IEntity))
		{
			return false;
		}
		IEntity other = (IEntity) o;

		// if the id is missing, return false
		if (id == null)
		{
			return false;
		}

		// equivalence by id
		return id.equals(other.getId());
	}

	@Override
	public int hashCode() 
	{
		if (id != null)
		{
			return id.hashCode();
		}
		else 
		{
			return super.hashCode();
		}
	}

	@Override
	public String toString() 
	{
		// TODO Auto-generated method stub
		return "id: " + id + ", createdAt: " + createdAt.toString()
				+ ", changedAt: " + changedAt.toString();
	}
}




import java.util.List;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import com.google.inject.name.Named;
import com.model.Role;
import com.wideplay.warp.persist.dao.Finder;

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "USER_TYPE", discriminatorType = DiscriminatorType.STRING)
@Table(name = "USER")
public abstract class BaseUser extends AbsEntity<BaseUser, String> implements IEntity<BaseUser, String> 
{
	 @Column(name = "EMAIL")
	 private String email;

	 @Column(name = "PASSWORD", length = 50)
	 private String password;

	 @Column(name = "FULL_NAME", length = 50)
	 private String fullName;

	 @Column(name = "ACTIVE")
	 private boolean active = true;
	  
	 @Column(name = "LOGIN_RANDOM_PASSWORD") 
	 private String loginRandomPassword;
	    
    @ManyToOne(targetEntity = Role.class)
    @JoinColumn(name = "FK_ROLE_ID")
    private Role role;
    
	/**
	 * Necessary to use the generic operation methods in AbsEntity.
	 */
	@SuppressWarnings("unchecked")
	public BaseUser()
	{
		super(BaseUser.class);
	}
	
	/** ********************************************** */
	/** Properties *********************************** */
	/** ********************************************** */

	public String getEmail() 
	{
		return email;
	}

	public void setEmail(String email) 
	{
		this.email = email;
	}

	public String getPassword()
	{
		return password;
	}

	public void setPassword(String password) 
	{
		this.password = password;
	}

	public String getFullName()
	{
		return fullName;
	}

	public void setFullName(String fullName) 
	{
		this.fullName = fullName;
	}

	public boolean isActive()
	{
		return active;
	}

	public void setActive(boolean active) 
	{
		this.active = active;
	}

	public String getLoginRandomPassword() 
	{
		return loginRandomPassword;
	}

	public void setLoginRandomPassword(String loginRandomPassword)
	{
		this.loginRandomPassword = loginRandomPassword;
	}

	public Role getRole() 
	{
		return role;
	}

	public void setRole(Role role)
	{
		this.role = role;
	}
		
	/** ********************************************** */
	/** Operators ************************************ */
	/** ********************************************** */

	// Override save, remove, find, and findAll methods as necessary.
	//
	/** ********************************************** */
	/** Custom Finders ******************************* */
	/** ********************************************** */
	@Finder(query = "FROM Role WHERE id = :roleId")
	public Role findRoleById(@Named("roleId")Long roleId) 
	{
		return null; // never called
	}
	
	@Finder(query = "From Role order by roleName")
	public List<Role> findAllRoles() 
	{
		return null;
	}


}



import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

import com.model.abs.BaseUser;

@Entity()
@DiscriminatorValue("C_USER")
public class CustomUser extends BaseUser 
{
	/** ********************************************** */
	/** Custom Finders ******************************* */
	/** ********************************************** */
}


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.inject.Inject;
import com.wideplay.warp.persist.PersistenceService;

public class InitializerJpa 
{
	private final Log log = LogFactory.getLog(getClass());

	@SuppressWarnings("unused")
	private final PersistenceService service;

	/**
	 * Starters the JPA persistence service.
	 * 
	 * @param service
	 *            the persistence service to start.
	 */
	@Inject
	InitializerJpa(PersistenceService service) 
	{
		this.service = service;

		service.start();
		log.info("JPA Persistence Service started...");
	}
}

这个Module就像applicationContext.xml的功能
import com.app.InitializerJpa;
import com.google.inject.AbstractModule;
import com.wideplay.warp.jpa.JpaUnit;


public class MainModule extends AbstractModule 
{
	protected void configure() 
	{
		bindConstant().annotatedWith(JpaUnit.class).to("Persist_Unit");

		// to automatically start up the persistence service
		bind(InitializerJpa.class).asEagerSingleton();
	}
}



Persist_Unit.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">

	<!-- A JPA Persistence Unit -->
	<persistence-unit name="Persist_Unit" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
 
		<!-- JPA entities can be registered here, but it's not necessary -->

		<properties>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost/ex_ddd"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="123"/>
            <property name="hibernate.connection.pool_size" value="1"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
			<property name="hibernate.hbm2ddl.auto" value="create"/> 
        </properties>
        
	</persistence-unit>

</persistence>

你可能感兴趣的:(java,Hibernate,xml,jpa,Google)