Issue
When I try to save user object to db, i get
Request processing failed; nested exception is
org.springframework.orm.hibernate5.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException
for SQL [insert into users (created_at, email, first_name, last_name, password, role_, status) values (?, ?, ?,
?, ?, 'User', ?)]; SQL state [S1009]; error code [0]; could not insert:
[com.hramyko.finalapp.entity.User]; nested exception
But when i use method save to update existing user all works correctly
My User entity
package com.hramyko.finalapp.entity;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.util.Date;
import java.util.Objects;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "role_")
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected int id;
protected String email;
protected String password;
@Column(name = "first_name")
protected String firstName;
@Column(name = "last_name")
protected String lastName;
@DateTimeFormat
@Column(name = "created_at")
protected Date createdAt;
@Column(name = "role_")
@Enumerated(EnumType.STRING)
protected Role role;
@Enumerated(EnumType.STRING)
protected Status status;
}
My service method
@Transactional
@Override
public User saveUser(User user) {
userValidator.validate(user);
user = userRepository.save(user);
return user;
}
My repository
package com.hramyko.finalapp.repository;
import com.hramyko.finalapp.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
User findUserByEmail(String email);
}
Did anyone have a similar problem? I've tried everything already.
Solution
Your inheritance is funky. You have annotations from conflicting inheritance strategies:
- Joined table:
@Inheritance(strategy = InheritanceType.JOINED)
- Single table with discriminator
@DiscriminatorColumn(name = "role_")
See Hibernate Inheritance Mapping
On top of that, you are trying to insert the instance from the root of the inheritance hierarchy: User
while you should be inserting a subclass instead.
Answered By - Lesiak