Spring Data JPA 实例

[url][/url][b]
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) 查询方法的创建

[/b]

[img]http://dl2.iteye.com/upload/attachment/0098/6205/494ba8b5-90fd-3d9a-b400-b0176e1dd703.png[/img]

[img]http://dl2.iteye.com/upload/attachment/0098/6207/68f3ec9c-fc19-3d75-b59d-821e339c6038.png[/img]


@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();
}

}

[url]http://docs.spring.io/spring-data/jpa/docs/1.6.0.RELEASE/reference/html/index.html[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值