- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我在我的项目中使用 Spring Data JPA 和 Hibernate JPA 提供程序。在我的服务中,我有一个方法,它在数据库中保存一个实体,而不是使用返回的对象,我尝试获取有关该实体的更多详细信息。因此,不会获取详细信息。在日志中,我只看到插入语句,没有选择详细信息。
这是我的代码:
配置:
@Configuration
@Profile("test")
@EnableJpaRepositories(basePackages = {"pl.lodz.uml.sonda.common.repositories"})
@EnableTransactionManagement
@PropertySource(value = "classpath:db.test.properties")
public class PersistenceConfigTest {
@Autowired
private Environment env;
@Value("classpath:sql/test-initialization.sql")
private Resource sqlInitializationScript;
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(env.getProperty("hibernate.showSQL", Boolean.class));
adapter.setGenerateDdl(env.getProperty("hibernate.hbm2ddl", Boolean.class));
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setPackagesToScan("pl.lodz.uml.sonda.common.domains");
entityManagerFactory.setJpaVendorAdapter(adapter);
Properties properties = new Properties();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
entityManagerFactory.setJpaProperties(properties);
return entityManagerFactory;
}
@Bean(name = "transactionManager")
public PlatformTransactionManager platformTransactionManager() {
EntityManagerFactory entityManagerFactory = entityManagerFactory().getObject();
return new JpaTransactionManager(entityManagerFactory);
}
@Bean
public DataSourceInitializer dataSourceInitializer() {
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScript(sqlInitializationScript);
DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource());
initializer.setDatabasePopulator(populator);
initializer.setEnabled(env.getProperty("db.initialization", Boolean.class));
return initializer;
}
@Bean
public ProbeService probeService() {
return new ProbeServiceImpl();
}
}
服务:
@Service
@Transactional
public class ProbeServiceImpl implements ProbeService {
@Autowired
private ProbeRepository probeRepository;
@Override
public Probe saveProbe(Probe probe) {
Probe saved = probeRepository.save(probe);
saved.getGroup().getName();
return saved;
}
}
简单测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
@ContextConfiguration(classes = {PersistenceConfigTest.class})
@Transactional
@TransactionConfiguration(defaultRollback = true)
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class
})
public class ProbeServiceImplTest {
@Autowired
private ProbeService probeService;
@Test
public void test() {
Probe probe = ProbeFixtures.generateProbeSample("Test one");
probe.setGroup(ProbeFixtures.generateProbeGroupSample(1));
Probe saved = probeService.saveProbe(probe);
System.out.println("Group name: " + saved.getGroup().getName());
}
}
实体:
@Entity
@Table(name = "probes")
public class Probe {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "probe_id")
private long probeId;
@Column(name = "probe_title", nullable = false)
private String title;
@Column(name = "probe_description", nullable = true)
private String description;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "probe_group_id", nullable = true)
private ProbeGroup group;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "probe_image_id", nullable = true)
private ProbeFile image;
@Column(name = "probe_published_date", nullable = false)
private Date published;
@Column(name = "probe_last_updated_date", nullable = false)
private Date updated;
@Column(name = "probe_expire_date", nullable = false)
private Date expires;
@Column(name = "probe_is_active", nullable = false)
private boolean isActive;
@OneToMany(mappedBy = "probe", fetch = FetchType.LAZY)
private List<Question> questions;
@OneToMany(mappedBy = "probe", fetch = FetchType.LAZY)
private List<Vote> votes;
public Probe() {
questions = new LinkedList<>();
votes = new LinkedList<>();
}
// getters & setters ...
@Entity
@Table(name = "probe_groups")
public class ProbeGroup {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "probe_group_id")
private long probeGroupId;
@Column(name = "probe_group_name", nullable = false, unique = true)
private String name;
@Column(name = "probe_group_description", nullable = true)
private String description;
@OneToMany(mappedBy = "group", fetch = FetchType.LAZY)
private List<Probe> probes;
public ProbeGroup() {
probes = new LinkedList<>();
}
// getters & setters ...
最后几行日志:
Hibernate: insert into probes (probe_description, probe_expire_date, probe_group_id, probe_image_id, probe_is_active, probe_published_date, probe_title, probe_last_updated_date) values (?, ?, ?, ?, ?, ?, ?, ?)
Group name: null
我还尝试在 save() 之后运行 spring data jpa 方法 - getOne(id),但它也不起作用(调用插入语句,不选择);
更新:我从我的服务和测试中删除了@Transactional 注释。现在,当我保存一个实体然后获取同一实体时,我在日志中有两个 sql 语句:插入和选择。也许我的问题是因为错误的持久性/事务配置。你怎么看?
最佳答案
这可能有点过时了,但我遇到了同样的问题,发现 hibernate 二级缓存是问题所在。
关于java - Spring 数据 JPA : Fetching data from entity just after save() method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25462416/
我正在运行此代码并在没有互联网连接的情况下进行测试: fetch(url, options) .then(res => { // irrelevant, as catch happens
function fetchHandler(evt) { console.log('request:' + evt.request.url); dealWithRequest(evt)
我在 AdventureWorks2016 上执行了两个示例查询,并得到了相同的结果。那么什么时候应该使用 NEXT 或 FIRST 关键字? select LastName + ' ' + Firs
我有以下查询: @Query("SELECT new de.projectemployee.ProjectEmployee(employee) " + "FROM ProjectEmpl
我正在尝试使用 fetch on react 来实现客户端登录。 我正在使用护照进行身份验证。我使用的原因 fetch而不是常规 form.submit() , 是因为我希望能够从我的快速服务器接收错
我正在尝试将我的 Aurelia 项目从 beta 版本升级到 3 月版本。 我遇到的错误之一是: Cannot find name 'Request'. 谷歌搜索会在 GitHub 上显示此问题:h
见标题。在我们的react项目中调用fetch时,一位(现已离职)开发人员最初使用from fetch to window.fetch。我不确定两者之间的区别,也无法在网上找到任何结论(W3Schoo
这个问题在这里已经有了答案: HTTP status code 401 even though I’m sending credentials in the request (1 个回答) How
这是代码片段: var fetch = require("node-fetch"); var fetchMock = require("fetch-mock"); function setupMock
我在这里看到了两种不同的抓取方式: https://github.com/github/fetch https://github.com/matthew-andrews/isomorphic-fetc
以下git命令有什么区别? git fetch origin 和 git fetch --all 从命令行运行它们看起来就像它们做同样的事情。 最佳答案 git fetch origin 仅从 ori
我有一个不断改变值的动态 json。我想用该数据绘制图表所以我将动态数据存储到数组然后用该数组绘制图表。目前我创建了 serinterval 用于从 api 获取新数据。但问题是如果新数据没有,它会再
我有一个很大的 JSON blob,我想预先加载我的网页。为此,我添加了 到我的页面。我也有一个 JS 请求来获取相同的 blob。 这不起作用,控制台报告: [Warning] The resour
我们在单页 JavaScript 应用程序发出 fetch 请求时遇到不一致的客户端错误。值得注意的是,它们都是同源请求。 let request = new Request(url, options
我是 ReactJS 的新手,我一直在阅读如何从 api 获取和发布数据。我见过这两个,但我不知道该用什么以及两者之间有什么区别?我读了它,但我不确定我会用什么。谢谢! react-fetch wha
Doctrine中注解@ManyToOne中的fetch="EAGER"和fetch="LAZY"有什么区别? /** * @ManyToOne(targetEntity="Cart", casca
我想要获取一个 api,然后调用另一个 api。在 javascript 中使用这样的代码是否明智? fetch(url, { method: 'get', }).then(function(re
我有一个组件,它依赖于 2 个端点来检索所需程序的名称。我有 2 个端点。第一个端点返回程序列表,它是一个对象数组。目前,它仅返回 4 个节目(2 个节目 ID 为“13”,另外两个节目 ID 为“1
我的应用程序从外部源(配置文件)接收查询,因此它必须从查询结果中获取列。我有一些代码: typedef union _DbField { text text[512]; sword i
我有一个实体A,它与实体B有对多关系。 Entity A -->> Entity B 我需要在多个屏幕上引用一对多关系的计数。此外,我可以多次从 Entity A
我是一名优秀的程序员,十分优秀!