我有一个带有一个简单实体和一个 JPA 存储库的 Spring 项目。该实体具有三个变量:Name (String)、active (boolean)和date (java.util.Date)。部署后,Hibernate 在我的 MySQL 数据库中使用varchar,tinyint和datetime. 一切似乎都正确,但是当我创建/修改实体的实例并调用save()存储库的方法时,除日期外的所有字段都被保存。使用 JPA 存储库存储日期是否有任何问题,或者我做错了什么?
我没有在这里放任何代码,因为它只是一个简单的类和存储库的接口。此外,实体正在被保存。我的问题仅与日期字段(以及我可以定义的任何其他日期字段)有关。话虽如此,如果有什么需要,尽管问。
编辑:
根上下文.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<import resource="infraestructure.xml" />
<jpa:repositories base-package="com.smarttabletv.repository" />
</beans>
Run Code Online (Sandbox Code Playgroud)
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context …Run Code Online (Sandbox Code Playgroud) 我尝试并阅读有关此问题的其他问题,但我无法将逻辑应用于我的案例.我想从这个表中选择:
@Entity
public class LabelStatistics {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int ID;
@Enumerated(EnumType.STRING)
private AnalysisType type;
private String labelId;
private String hexLabelId;
private Timestamp timestamp;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<LabelStatisticsItem> results;
Run Code Online (Sandbox Code Playgroud)
我正在尝试执行以下语句:
@Query(value = "SELECT s1.labelId, s1.type, s1.timestamp "
+ "FROM LabelStatistics s1 "
+ "INNER JOIN LabelStatistics s2 on s1.labelId = s2.labelId and s1.type = s2.type and s1.timestamp < s2.timestamp")
List<Object[]> findLatestStatisticsEntries();
Run Code Online (Sandbox Code Playgroud)
我一直收到这个错误:
org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join!
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下如何解决这个问题吗?最好的祝福
是否可以@Value从另一个变量设置
例如.
System properties : firstvariable=hello ,secondvariable=world
@Value(#{systemProperties['firstvariable'])
String var1;
Run Code Online (Sandbox Code Playgroud)
现在我想要var2与var1它连接并依赖它,就像这样
@Value( var1 + #{systemProperties['secondvariable']
String var2;
public void message(){ System.out.printlng("Message : " + var2 );
Run Code Online (Sandbox Code Playgroud) spring spring-annotations spring-data spring-boot spring-config
我需要将Spring依赖项注入到JPA实体侦听器中。我知道我可以使用@Configurable和Spring的AspectJ weaver作为javaagent来解决此问题,但这似乎是一个棘手的解决方案。还有其他方法可以完成我想做的事情吗?
我对这个独特的约束功能感到非常惊讶.我正在使用H2数据库开发一个弹簧启动应用程序进行单元测试.
我的一个实体有一个独特的约束.在User类的标题下面.
@Entity
@Table(name = "user", uniqueConstraints = { @UniqueConstraint(columnNames = { "identifier" }) })
@SequenceGenerator(name = "user_pkey", sequenceName = "user_id_seq")
Run Code Online (Sandbox Code Playgroud)
我写了一个小单元测试来检查唯一约束.
测试前功能
@Before
public void before() {
User user1 = new User();
user1.setBlackListed(false);
user1.setIdentifier("test@tby.com");
user1.setRefreshToken("azerty");
this.userDao.save(user1);
}
Run Code Online (Sandbox Code Playgroud)
我的考试
@Test(expected = DataIntegrityViolationException.class)
public void user_identifierUnicityTest() {
User user4 = new User();
user4.setBlackListed(false);
user4.setIdentifier("test@tby.com");
user4.setRefreshToken("azerty4");
User response = this.userDao.save(user4);
this.userDao.findByIdentifier("test@tby.com");
}
Run Code Online (Sandbox Code Playgroud)
我很惊讶,我认为在保存请求期间会抛出异常.或者在查找请求期间抛出异常.
在选择请求期间检查约束完整性而不是插入.我不明白结果.
这是唯一约束的正常行为吗?
谢谢你的回答:)
在我的控制器中我使用CrudRepository方法findAll()来查找我的数据库中的所有用户,如下所示:
userRepository.findAll()
Run Code Online (Sandbox Code Playgroud)
问题是,这样做需要1.3分钟才能加载1.500个用户.从那里我用Thymeleaf在模型中加载数据我在一个html表中显示它:名称,时间创建,电子邮件,id,数据包和每个用户的状态.有没有办法提高性能或解决我的问题?任何帮助都会非常准确.
这是我的用户实体
@Id
@SequenceGenerator(name = "user_id_generator", sequenceName = "user_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_generator")
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(name = "uuid", nullable = false, unique = true)
private String uuid;
@Column(name = "reset_pwd_uuid", unique = true)
private String resetPwdUuid;
@Column(nullable = false)
private String password;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Status status;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Packet packet = Packet.BASE;
@Enumerated(EnumType.STRING)
@Column
private Situation situation; …Run Code Online (Sandbox Code Playgroud) 我正在尝试发布一个用户组:
public UserGroup createUserGroup(UserGroup userGroup) {
ResponseEntity<UserGroup> userGroupResponseEntity = oauthRestTemplate
.postForEntity(GROUPS_ENDPOINT, userGroup, UserGroup.class);
return userGroupResponseEntity.getBody();
}
Run Code Online (Sandbox Code Playgroud)
由于我正在使用@RepositoryRestResource,因此必须配置对象映射器:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new Jackson2HalModule());
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setObjectMapper(objectMapper);
messageConverter.setSupportedMediaTypes(Collections.singletonList(MediaTypes.HAL_JSON));
this.oauthRestTemplate.setMessageConverters(Collections.singletonList(messageConverter));
Run Code Online (Sandbox Code Playgroud)
但是,从上面运行POST会抛出我
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected VALUE_STRING: Expected array or string.
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 1, column: 87] (through reference chain: mahlzeit.api.hibernate.model.UserGroup["voteUntil"])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63) ~[jackson-databind-2.9.4.jar:2.9.4]
at com.fasterxml.jackson.databind.DeserializationContext.wrongTokenException(DeserializationContext.java:1507) ~[jackson-databind-2.9.4.jar:2.9.4]
at com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer.deserialize(LocalDateTimeDeserializer.java:138) ~[jackson-datatype-jsr310-2.9.2.jar:2.9.2]
at com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer.deserialize(LocalDateTimeDeserializer.java:39) ~[jackson-datatype-jsr310-2.9.2.jar:2.9.2]
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127) ~[jackson-databind-2.9.4.jar:2.9.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:369) ~[jackson-databind-2.9.4.jar:2.9.4] …Run Code Online (Sandbox Code Playgroud) 是否可以在@Query批注内调用参数的方法?
例:
@Query("SELECT user " +
"FROM User user " +
"WHERE (?1.getFilter() = '*' OR user.name = ?1)");
List<User> getUsers(UserNameFilter userNameFilter);
Run Code Online (Sandbox Code Playgroud)
我知道我可以做这样的事情:
@Query("SELECT user " +
"FROM User user " +
"WHERE (?1 = '*' OR user.name = ?1)");
List<User> getUsers(String userName);
Run Code Online (Sandbox Code Playgroud)
但是,当过滤器数量增加时,这意味着我需要更改许多参数。
我正在尝试检查用户名在spring-boot中是否唯一。我想将结果作为JSON对象发送。这是REST控制器
@RequestMapping(value="/checkEmailUnique",method=RequestMethod.POST)
public String checkEmailUnique(@RequestBody String username){
AppUser app = userRepo.findByUsername(username);
if(app!=null){
// I want to return somthing like emailNotTaken: true
}
else{
// and here : emailNotTaken: false
}
}
Run Code Online (Sandbox Code Playgroud)
我想获得角度结果,以便在组件中显示错误消息。我怎样才能做到这一点?
角边
客户服务
checkEmailNotTaken(email:string){
if(this.authService.getToken()==null) {
this.authService.loadToken();
}
return this.http.post(this.host+
"/checkEmailUnique/",{email},{headers:new HttpHeaders({'Authorization':this.authService.getToken()})});
}
Run Code Online (Sandbox Code Playgroud)
在client.component.ts中
ngOnInit() {
this.form = this.formBuilder.group({
prenom: ['', Validators.required],
nom: ['', Validators.required],
tel: ['', Validators.required],
cin: ['', Validators.required],
username: ['', Validators.required , Validators.email , this.validateEmailNotTaken.bind(this)],
passwordG: this.formBuilder.group({
password: ['',[Validators.required,Validators.minLength(9)]],
Confirmationpassword : ['',[Validators.required,Validators.minLength(9)]]
}, {validator: passwordMatch})
}); …Run Code Online (Sandbox Code Playgroud) 我基于Spring Initializr(渐变风味)创建了一个Spring Boot应用程序。
我还加了
compile('org.springframework.boot:spring-boot-starter-data-mongodb')
Run Code Online (Sandbox Code Playgroud)
使用MongoDB进行持久化。我还添加了一个可以正常工作的简单集成测试:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TileServiceApplicationTests {
@Autowired
private MockMvc mvc;
@Autowired
private UserSettingRepository userSettingRepository;
@Test
public void contextLoads() throws Exception {
Folder folder = random( Folder.class, "color", "elements" );
EserviceTile eserviceTile1 = random( EserviceTile.class , "color");
EserviceTile eserviceTile2 = random( EserviceTile.class, "color" );
folder.setElements( Arrays.asList(eserviceTile1) );
TileList usersTiles = new TileList( Arrays.asList( folder, eserviceTile2 ) );
userSettingRepository.save( new UserSetting( "user1", usersTiles ));
String string = mvc.perform( get( "/user1" ) ).andExpect( status().isOk() …Run Code Online (Sandbox Code Playgroud)