`
CherryRemind
  • 浏览: 53757 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

'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>

分享到:
评论

相关推荐

    blog(guice+hibernate+warp)

    A sample Java web application that demonstrates how &lt;br&gt;Deployment : * Install Dekoh desktop * Start dekoh in interactive mode by executing dekoh_shell.bat / dekoh_shell.sh in directory C:...

    guice.jar/guice.jar

    guice.jar guice.jar guice.jar guice.jar guice.jar guice.jar guice.jar

    Guice+Struts2+warp-persist 简单实例

    借助Guice+Struts2+Warp-persist来构建一个比较轻盈的web开发框架,目的是想抛砖引玉。随后还会将Scala部分整合进来,目的就是唯恐框架不烂!(*^__^*)。 对于代码的不妥之处欢迎各路高手斧正。 mail to : meconsea@...

    Google Guice: Agile Lightweight Dependency Injection Framework

    * Learn simple annotation-driven dependency injection, scoping and AOP, and why it all works the way it works. * Be the first to familiarize yourself with concepts that are likely to be included in ...

    guice入门学习资料

    guice 学习资料,快速掌握guice的编程技巧以及了解其机制。

    guice-3.0-API文档-中英对照版.zip

    赠送jar包:guice-3.0.jar; 赠送原API文档:guice-3.0-javadoc.jar; 赠送源代码:guice-3.0-sources.jar; 赠送Maven依赖信息文件:guice-3.0.pom; 包含翻译后的API文档:guice-3.0-javadoc-API文档-中文(简体)-...

    guice-multibindings-3.0-API文档-中文版.zip

    赠送jar包:guice-multibindings-3.0.jar; 赠送原API文档:guice-multibindings-3.0-javadoc.jar; 赠送源代码:guice-multibindings-3.0-sources.jar; 赠送Maven依赖信息文件:guice-multibindings-3.0.pom; ...

    google guice基础例子

    Guice是Google开发的一个轻量级,基于Java5(主要运用泛型与注释特性)的依赖注入框架(IOC)。Guice非常小而且快。Guice是类型安全的,它能够对构造函数,属性,方法(包含任意个参数的任意方法,而不仅仅是setter...

    Guice用户中文指南

    Guice用户中文指南,Guice (读作"juice")是超轻量级的,下一代的,为Java 5及后续版本设计的依赖注入容器

    Guice_1.0_Manual.pdf

    Guice开发手册, Guice中文开发手册

    guice-3.0-API文档-中文版.zip

    赠送jar包:guice-3.0.jar; 赠送原API文档:guice-3.0-javadoc.jar; 赠送源代码:guice-3.0-sources.jar; 赠送Maven依赖信息文件:guice-3.0.pom; 包含翻译后的API文档:guice-3.0-javadoc-API文档-中文(简体)版...

    guice-2.0.jar

    guice-2.0.jar guice-2.0.jar

    google guice 3.0源码

    google guice 3.0源码,官方下载,帮助你更好理解google guice实现的原理

    guice-3.0.rar

    guice-3.0,轻量级IOC容器,包含guice-3.0.jar、guice-spring-3.0.jar、guice-struts2-plugin-3.0.jar

    guice-4.0-API文档-中文版.zip

    赠送jar包:guice-4.0.jar; 赠送原API文档:guice-4.0-javadoc.jar; 赠送源代码:guice-4.0-sources.jar; 赠送Maven依赖信息文件:guice-4.0.pom; 包含翻译后的API文档:guice-4.0-javadoc-API文档-中文(简体)版...

    guice-multibindings-3.0-API文档-中英对照版.zip

    赠送jar包:guice-multibindings-3.0.jar; 赠送原API文档:guice-multibindings-3.0-javadoc.jar; 赠送源代码:guice-multibindings-3.0-sources.jar; 赠送Maven依赖信息文件:guice-multibindings-3.0.pom; ...

    shiro,guice集成

    shiro,guice集成,官方资料,精准全面

    guice-assistedinject-3.0-API文档-中英对照版.zip

    赠送jar包:guice-assistedinject-3.0.jar; 赠送原API文档:guice-assistedinject-3.0-javadoc.jar; 赠送源代码:guice-assistedinject-3.0-sources.jar; 赠送Maven依赖信息文件:guice-assistedinject-3.0.pom;...

    guice超轻量级依赖注入

    guice超轻量级依赖注入用了才知道是爽

Global site tag (gtag.js) - Google Analytics