我正在使用Spring Boot 1.3.0.M4和MySQL数据库.
我在使用修改查询时遇到问题,EntityManager在执行查询后包含过时的实体.
public interface EmailRepository extends JpaRepository<Email, Long> {
@Transactional
@Modifying
@Query("update Email e set e.active = false where e.active = true and e.expire <= NOW()")
Integer deactivateByExpired();
}
Run Code Online (Sandbox Code Playgroud)
假设我们在DB中有Email [id = 1,active = true,expire = 2015/01/01].
执行后:
emailRepository.save(email);
emailRepository.deactivateByExpired();
System.out.println(emailRepository.findOne(1L).isActive()); // prints true!! it should print false
Run Code Online (Sandbox Code Playgroud)
public interface EmailRepository extends JpaRepository<Email, Long> {
@Transactional
@Modifying(clearAutomatically = true)
@Query("update Email e set e.active = false where e.active = true and …Run Code Online (Sandbox Code Playgroud) 让我们假设有这种情况:
我们以标准方式配置弹簧数据,有一个Respository对象,一个Entity对象,一切运行良好.
现在,对于一些复杂的动机,我必须直接使用EntityManager(或者JdbcTemplate,比弹簧数据更低的级别)Entity使用本机sql查询来更新与我相关联的表.所以我没有使用Entity对象,只是简单地在我用作实体的表上手动进行数据库更新(更准确地说是从中获取值的表,请参阅下一行).原因是我必须将我的spring-data绑定Entity到一个mysql视图,该视图使UNION成为多个表,而不是直接到我需要更新的表.
会发生什么:
在功能测试中,我称之为"手动"更新方法(在创建mysql视图的表上)(通过实体管理器)和如果我做一个简单的Respository.findOne(objectId)我得到旧对象(没有更新一个).我打电话Entitymanager.refresh(object)来获取更新的对象.
为什么?
有没有办法在spring-data中"同步"(开箱即用)对象(或强制刷新一些)?还是我要求奇迹?我不讽刺,但也许我不是那么专家,也许(或可能)是我的无知.如果是这样,请解释我为什么和(如果你想)分享一些关于这个惊人框架的高级知识.
我有以下服务:
@Service
public class CamelService {
@Transactional
public aCamelThing() {
Camel camel = this.camelRepository.findOne(1);
System.out.println(camel.getCamelName()); // prints "normalCamel"
// simple hql set field 'camelName'
int res = this.camelRepository.updateCamelName(1,"superCamel!");
Camel camelWithNewName = this.camelRepository.findOne(1);
System.out.println(camelWithNewName .getCamelName()); // prints "normalCamel" ?!?!?
}
}
Run Code Online (Sandbox Code Playgroud)
我知道如何实现第二张println打印的目标:"superCamel!" ?(将第二次调用与新事务分开并不理想).
我正在开发一个基于 Spring 的服务器。我有两个Controllers正在侦听不同的 http 请求。它们都有一个引用Repository与@Autowired注释相同的变量。
@Controller
public class ClientController {
@Autowired
NodeRepository nodeRepository;
...
}
@Controller
public class NodeController {
@Autowired
NodeRepository nodeRepository;
...
}
Run Code Online (Sandbox Code Playgroud)
所有的数据库操作都是通过使用NodeRepository:
public interface NodeRepository extends JpaRepository<Node, Long>{
Node findByNodeId(long nodeId);
List<Node> findByStatusIn(Set<String> status);
List<Node> findByNodeIdIn(Set<Long> ids);
Node findByPhoneNumber(String phoneNumber);
Node findByCloudId(String cloudId);
Node findByDeviceDescription(String deviceDescription);
}
Run Code Online (Sandbox Code Playgroud)
行为如下:
当ClientController接收到一个新的请求时,它被处理并且控制器向外部设备发送一个请求并等待它的答复。
这个答案是由NodeController. 因此,当答案到达时,接收到的信息将保存在数据库中,并向 发送信号ClientController以唤醒它。
当这个控制器被唤醒并试图从数据库中检索更新的信息时,我的问题就出现了。该信息不是刚刚存储的信息,而是之前存储的信息。
这是ClientController块和检索信息发生的代码片段:
// Retrieves the list of nodes …Run Code Online (Sandbox Code Playgroud)