我不可能有真正发生的更新
Updatequery
@Entity
@ToString(callSuper = true)
// query just for logging purposes
@NamedQuery(name="TestEntity.findAll", query="SELECT t FROM TestEntity t")
public class TestEntity {
@Id
@GeneratedValue
private Long id;
private String message = "not altered";
}
还有一个测试,比如:
@Slf4j
@DataJpaTest
@org.springframework.transaction.annotation.Transactional(propagation =
Propagation.NOT_SUPPORTED)
@RunWith(SpringRunner.class)
public class TestEntityUpdateTest {
@PersistenceContext
private EntityManager em;
private void buildTestEntity(int i) {
em.persist(new TestEntity());
}
private void log(Object o) {
log.info("\n{}", o);
}
@Test
@Transactional
public void testUpdate() {
IntStream.range(1, 4).forEach(this::buildTestEntity);
TypedQuery<TestEntity> tq =
em.createNamedQuery("TestEntity.findAll", TestEntity.class);
// log inserted stuff
log.info("\nINSERTED rows");
tq.getResultList().forEach(this::log);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaUpdate<TestEntity> update =
cb.createCriteriaUpdate(TestEntity.class);
Root<TestEntity> from = update.from(TestEntity.class);
update.set(from.get("message"), "ALTERED TEXT!");
int i = em.createQuery(update).executeUpdate();
log.info("\nUPDATED {} rows", i);
// log updated stuff
tq.getResultList().forEach(this::log);
}
}
一定很简单,但我看不出来是什么?我也试过了
em.flush()
在任何可以想象的地方。
要加点吗
commit()
或者某个Spring数据设置?
行插入正确。我可以看到相应的日志行,例如:
TestEntity(super=org.example.spring.entity.updatequery。TestEntity@230a73f2,
我可以看到更新查询和绑定正确(?):
更新
测试实体
设置
....
更新后,我看不到更改,但:
TestEntity(super=org.example.spring.entity.updatequery。TestEntity@230a73f2,
相关部件
pom.xml
(要求更多):
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
...