List
List
List
void flush();//执行缓存与数据库同步
T saveAndFlush(T entity);//强制执行持久化
例如: 定义一个Entity实体类
class User{
private String firstname;
private String lastname;
使用And条件连接时,应这样写:
findByLastnameAndFirstname(String lastname,String firstname);
(1)在Entity实体类上使用@NamedQuery注解直接声明命名查询。
@Entity
@NamedQuery(name = "User.findByEmailAddress",
query = "select u from User u where u.emailAddress = ?1")
public class User {
}
注:定义多个时使用下面的注解
@NamedQueries(value = {
@NamedQuery(name = User.QUERY_FIND_BY_LOGIN,
query = "select u from User u where u." + User.PROP_LOGIN
+ " = :username"),
@NamedQuery(name = "getUsernamePasswordToken",
query = "select new com.aceona.weibo.vo.TokenBO(u.username,u.password) from User u where u." + User.PROP_LOGIN
+ " = :username")})
(2)在interface中定义与(1)对应的方法
public interface UserRepository extends JpaRepository
List
User findByEmailAddress(String emailAddress);
@Query("select u from User u where u.emailAddress = ?1")
User findByEmailAddress(String emailAddress);
@Query与 @Modifying 执行更新操作
这两个annotation一起声明,可定义个性化更新操作,例如只涉及某些字段更新时最为常用,示例如下:
@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
索引参数与命名参数
(1)索引参数如下所示,索引值从1开始,查询中 ”?X” 个数需要与方法定义的参数个数相一致,并且顺序也要一致
@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);
(2)命名参数(推荐使用这种方式)
可以定义好参数名,赋值时采用@Param("参数名"),而不用管顺序。如下所示:
public interface UserRepository extends JpaRepository
@Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
User findByLastnameOrFirstname(@Param("lastname") String lastname,
@Param("firstname") String firstname);
@org.springframework.stereotype.Repository
@Transactional(readOnly = true)
public class SimpleJpaRepository
JpaSpecificationExecutor
……
@Transactional
public void delete(ID id) {
delete(findOne(id));
}
……
进行多个Repository操作时,也应该使它们在同一个事务中处理,按照分层架构的思想,这部分属于业务逻辑层,因此,需要在Service层实现对多个Repository的调用,并在相应的方法上声明事务。
例如:
@Service(“userManagement”)
class UserManagementImpl implements UserManagement {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
@Autowired
public UserManagementImpl(UserRepository userRepository,
RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
@Transactional
public void addRoleToAllUsers(String roleName) {
Role role = roleRepository.findByName(roleName);
for (User user : userRepository.readAll()) {
user.addRole(role);
userRepository.save(user);
}
对于不需要写实现类的情况:
定义XxxxRepository 接口并继承JpaRepository接口,
定义XxxxDao 接口并继承com.aceona.appleframework.persistent.data.GenericDao
书写XxxxDaoImpl实现类并继承com.aceona.appleframework.persistent.data.GenericJpaDao,
同时实现XxxxDao接口中的方法