CrudRepository 不保存数据
CrudRepository doesn't save data
我在通过 CrudRepository 将新对象保存到数据库时遇到问题。有趣的是我可以从存储库中读取数据。
所以,当我获取数据时,我在控制台中有一个 SQL 查询。
当我保存数据时,控制台是空的。此外,CrudRepository.save returns 一个有效的对象,分配了 id。
你能看看吗?
提前谢谢你。
控制器class:
@Controller
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Iterable<User>> viewUsers() {
return ResponseEntity.ok(userRepository.findAll());
}
@PutMapping(value = "/users/add", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> addUser(@RequestBody User user) {
User persisted = userRepository.save(user);
System.out.println(persisted);
if (persisted == null) {
return new ResponseEntity<>("Error while saving user", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>("OK", HttpStatus.CREATED);
}
}
实体class:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(generator = "system-uuid2")
@GenericGenerator(name = "system-uuid2", strategy = "uuid2")
private String id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("User{");
sb.append("id='").append(id).append('\'');
sb.append(", firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", email='").append(email).append('\'');
sb.append(", password='").append(password).append('\'');
sb.append('}');
return sb.toString();
}
}
sql 其中 table 创建:
CREATE TABLE USER(
ID VARCHAR(255) NOT NULL UNIQUE,
FIRST_NAME VARCHAR(255) NOT NULL,
LAST_NAME VARCHAR(255) NOT NULL,
EMAIL VARCHAR(255) NOT NULL,
PASSWORD VARCHAR(255) NOT NULL,
PRIMARY KEY (ID)
);
基于和java的配置:
@Configuration
@EnableJpaRepositories(basePackages = "ua.maximenko.jquizful.repository")
@EnableTransactionManagement
@EnableWebMvc
public class Config implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true).simpleDateFormat("yyyy-MM-dd HH:mm:ss");
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
return dbBuilder
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:sql/create-tables.sql")
.addScript("classpath:sql/populate-tables.sql")
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setJpaVendorAdapter(adapter);
factoryBean.setDataSource(dataSource());
return factoryBean;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactory().getNativeEntityManagerFactory());
return tm;
}
}
用户资料库:
package ua.maximenko.jquizful.repository;
import org.springframework.data.repository.CrudRepository;
import ua.maximenko.jquizful.domain.User;
public interface UserRepository extends CrudRepository<User, String> {
}
还附加了带有项目结构的屏幕
如果需要任何其他信息,请告诉我。
我认为这个配置是错误的:
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactory().getNativeEntityManagerFactory());
return tm;
}
您必须在 EntityManagerFactory 上调用 getObject()
:
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactory().getObject());
return tm;
}
我在通过 CrudRepository 将新对象保存到数据库时遇到问题。有趣的是我可以从存储库中读取数据。
所以,当我获取数据时,我在控制台中有一个 SQL 查询。 当我保存数据时,控制台是空的。此外,CrudRepository.save returns 一个有效的对象,分配了 id。
你能看看吗? 提前谢谢你。
控制器class:
@Controller
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Iterable<User>> viewUsers() {
return ResponseEntity.ok(userRepository.findAll());
}
@PutMapping(value = "/users/add", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> addUser(@RequestBody User user) {
User persisted = userRepository.save(user);
System.out.println(persisted);
if (persisted == null) {
return new ResponseEntity<>("Error while saving user", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>("OK", HttpStatus.CREATED);
}
}
实体class:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(generator = "system-uuid2")
@GenericGenerator(name = "system-uuid2", strategy = "uuid2")
private String id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("User{");
sb.append("id='").append(id).append('\'');
sb.append(", firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", email='").append(email).append('\'');
sb.append(", password='").append(password).append('\'');
sb.append('}');
return sb.toString();
}
}
sql 其中 table 创建:
CREATE TABLE USER(
ID VARCHAR(255) NOT NULL UNIQUE,
FIRST_NAME VARCHAR(255) NOT NULL,
LAST_NAME VARCHAR(255) NOT NULL,
EMAIL VARCHAR(255) NOT NULL,
PASSWORD VARCHAR(255) NOT NULL,
PRIMARY KEY (ID)
);
基于和java的配置:
@Configuration
@EnableJpaRepositories(basePackages = "ua.maximenko.jquizful.repository")
@EnableTransactionManagement
@EnableWebMvc
public class Config implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true).simpleDateFormat("yyyy-MM-dd HH:mm:ss");
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
return dbBuilder
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:sql/create-tables.sql")
.addScript("classpath:sql/populate-tables.sql")
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setJpaVendorAdapter(adapter);
factoryBean.setDataSource(dataSource());
return factoryBean;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactory().getNativeEntityManagerFactory());
return tm;
}
}
用户资料库:
package ua.maximenko.jquizful.repository;
import org.springframework.data.repository.CrudRepository;
import ua.maximenko.jquizful.domain.User;
public interface UserRepository extends CrudRepository<User, String> {
}
还附加了带有项目结构的屏幕
如果需要任何其他信息,请告诉我。
我认为这个配置是错误的:
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactory().getNativeEntityManagerFactory());
return tm;
}
您必须在 EntityManagerFactory 上调用 getObject()
:
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactory().getObject());
return tm;
}