`
TRAMP_ZZY
  • 浏览: 131981 次
社区版块
存档分类
最新评论

Spring Data JPA 实例

阅读更多
[url][/url]
1. Sping Data JPA 创建查找的顺序
a. CREATE attempts to construct a store-specific query from the query method name. The general approach is to remove a given set of well-known prefixes from the method name and parse the rest of the method. Read more about query construction in the section called “Query creation”.
b. USE_DECLARED_QUERY  tries to find a declared query and will throw an exception in case it can't find one. The query can be defined by an annotation somewhere or declared by other means. Consult the documentation of the specific store to find available options for that store. If the repository infrastructure does not find a declared query for the method at bootstrap time, it fails.
c. CREATE_IF_NOT_FOUND (default) combines CREATE and USE_DECLARED_QUERY. It looks up a declared query first, and if no declared query is found, it creates a custom method name-based query. This is the default lookup strategy and thus will be used if you do not configure anything explicitly. It allows quick query definition by method names but also custom-tuning of these queries by introducing declared queries as needed.

2. 查询创建机制
(1) 有用的前缀 find…By, read…By, query…By, count…By, and get…By,同时可以在查询语句前面加上 Distinct 来创建语句。
(2) 查询方法的创建







@Repository
public class UserDaoImpl implements UserDao {

	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	public User findByName(String name) {
		TypedQuery<User> query = this.entityManager.createQuery("select u from User u where u.name = :name",
				User.class);
		query.setParameter("name", name);
		return query.getSingleResult();
	}

	@Override
	public List<User> findAll() {
		TypedQuery<User> query = this.entityManager.createQuery("select u from User u", User.class);
		return query.getResultList();
	}

	@Override
	public void saveOrUpdate(User user) {
			this.entityManager.persist(user);
	}
}

@NoRepositoryBean
public interface AbstractRepository<T extends AbstractEntity> extends Repository<T, Long> {
	  @Query("select t from #{#entityName} t where t.id = ?1")
	  List<T> findAllById(Long id);
}

@MappedSuperclass
public class AbstractEntity {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	/**
	 * Returns the identifier of the entity.
	 * 
	 * @return the id
	 */
	public Long getId() {
		return id;
	}

	/* 
	 * (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {

		if (this == obj) {
			return true;
		}

		if (this.id == null || obj == null || !(this.getClass().equals(obj.getClass()))) {
			return false;
		}

		AbstractEntity that = (AbstractEntity) obj;

		return this.id.equals(that.getId());
	}

	/* 
	 * (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		return id == null ? 0 : id.hashCode();
	}
	
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}

public interface UserRepository extends Repository<User, Integer>, UserRepositoryCustom {
	List<User> findByNameAndEmail(String name, String email);
	
	// Enable the distinct flag for the query
	List<User> findDistinctUserByNameOrEmail(String name, String email);
	List<User> findUserDistinctUserByNameOrEmail(String name, String email);
	
	//  Enabling ignoring case for an individual property
	List<User> findByNameIgnoreCase(String name);
	// Enabling static ORDER BY for a query
	List<User> findByNameAndEmailAllIgnoreCase(String name, String email);
	
	// Enabling static ORDER BY for a query
	@Lock(LockModeType.READ)
	List<User> findByNameOrderByUserIdAsc(String name);
	List<User> findByNameOrderByUserIdDesc(String name);
	
	
	Page<User> findByNameLike(String name, Pageable pageable);
	List<User> findByNameLike(String name, Sort sort);
	
	// User @Query
	@Query("select u from User u where u.email = ?1")
	User findByEmail(String email);
	@Query("select u from User u where u.name like %?1")
	List<User> findByNameEndsWith(String name);
	
	//User @Query to execute Navtie Query
	@Query(value = "select * from user where email = ?0", nativeQuery = true)
	User findByEmailAddress(String email);
	
	// Modify 
	@Modifying(clearAutomatically = true)
	@Query("update User u set u.name = ?1 where u.id = ?2")
	int setFixedNameFor(String name, Integer id);
}

/*
 * 选用CrudRepository 接口是为了暴露方法,因为默认的SimpleJpaRepository 已经实现了很多方法
 * 必须暴露出来,才能调用
 */
public interface ProductRepository extends CrudRepository<Product, Long>{
	
	public abstract Page<Product> findByDescriptionContaining(String description, Pageable pageable);
	
	@Query("select p from Product p where p.attributes[?1] = ?2")
	public abstract List<Product> findByArrtibuteAndValue(String attribute, String value);
	
	public abstract Long countByName(String name);
	
	public List<Product> findByName(String name);
	
}

public interface DocumentRepository extends JpaRepository<Document, Integer>, 
		CrudRepository<Document, Integer>{
	List<Document> findByDocName(String docName);
	
	@Query(value="select d from Document d where d.docType=:docType")
	public Document findByDocType(@Param("docType") Byte docType);
	
	public List<Document> findByUploadAuthorLike(String uploadAuthor);
	
	@Query("select d from Document d where d.author=:author")
	public List<Document> findByAuthorLike(String author);
	
	public List<Document> findByDocTypeBetween(Byte begin, Byte end);
	
}

@Repository
@Transactional(readOnly = true)
public class JpaCustomerDaoImpl implements CustomerDao {

	@PersistenceContext
	private EntityManager em;
	
	@Override
	@Transactional
	public Customer save(Customer customer) {
		if (customer.getId() != null) {
			em.persist(customer);
			return customer;
		} else {
			return em.merge(customer);
		}
	}

	@Override
	public Customer findByEmailAddress(EmailAddress emailAddress) {
		String sql = " select c from Customer c where c.emailAddress = :emailAddress";
		TypedQuery<Customer> query = em.createQuery(sql, Customer.class);
		query.setParameter("emailAddress", emailAddress);
		return query.getSingleResult();
	}

}

http://docs.spring.io/spring-data/jpa/docs/1.6.0.RELEASE/reference/html/index.html
  • 大小: 92 KB
  • 大小: 48.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics