Column doesn`t exist - java

Try to learn hibernate + jpa, don`t know what to do with this. Error when getting by id.
JDBC exception executing SQL [select u1_0.id,u1_0.email,u1_0.login,u1_0.password,r1_0.id,r1_0.name from user u1_0 left join role r1_0 on r1_0.id=u1_0.role_id where u1_0.id=?]
Caused by: org.postgresql.util.PSQLException: ERROR: column u1_0.role_id doesn`t exist
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(nullable = false, unique = true)
private String login;
#Column(nullable = false)
private String password;
#Column(nullable = false, unique = true)
private String email;
#ManyToOne
#JoinColumn(name = "role_id")
private UserRole role;
}
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity
#Table(name = "role")
public class UserRole {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(nullable = false)
private String name;
}
enter image description here
Tried to debug but no results

Related

How to create a JPA entity which has a field(s) from another entity?

I have the following entity in SpringBoot and I would like to create a new entity which has the userID of the registered user and the name of the registered/logged in user as instance fields/table columns.
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name="User")
public class WebUser {
#Id
#GeneratedValue
private Long userID;
#NonNull
private String name;
#NonNull
private String email;
#NonNull
private String password;
}
How would I go about doing this using a form in SpringBoot and JPA entity? I am struggling, I tried to create a form with hidden input fields using #OneToMany annotation but the userID and name were null.
Thanks for any help
Frist of all you Should define table column names using #Column(name = "COLUMN_NAME") and assume your new entity name LogUser.
LogUser
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name="LogUser")
public class LogUser{
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", nullable = false)
private WebUser webUser;
#Column(name = "NAME", nullable = false)
private String name;
}
WebUser
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name="User")
public class WebUser {
#Id
#GeneratedValue
#Column(name = "USER_ID")
private Long userID;
#Column(name = "NAME", nullable = false)
private String name;
#Column(name = "EMAIL", nullable = false)
private String email;
#Column(name = "PASSWORD", nullable = false)
private String password;
#OneToMany(mappedBy = "webUser")
private Set<LogUser> logUsers;
}

mappedBy reference an unknown target entity property role based

1 user ==> many roles
1- role ==> many components
for this I have configured like
userDao.java
#Entity
#Table(name = "User_info")
public class UserDao {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
#Column(name="username")
private String username;
#Column(name="password")
#JsonIgnore
private String password;
#ManyToMany(cascade=CascadeType.MERGE,fetch = FetchType.EAGER)
#JoinTable(
name="user_role",
joinColumns={#JoinColumn(name="USER_ID", referencedColumnName="userId")},
inverseJoinColumns={#JoinColumn(name="ROLE_ID", referencedColumnName="roleId")})
private List<Role> roles;
Role.java
#Entity
#Table(name = "roles")
public class Role {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
private Integer roleId;
#Column(nullable = false, unique = true)
#NotEmpty
private String roleName;
#ManyToMany(mappedBy = "roles")
private List < UserDao > users;
#ManyToMany(cascade=CascadeType.MERGE,fetch = FetchType.EAGER)
#JoinTable(
name="role_component",
joinColumns={#JoinColumn(name="ROLE_ID", referencedColumnName="roleId")},
inverseJoinColumns={#JoinColumn(name="COMP_ID", referencedColumnName="compId")})
private List<Component> components;
component.java
#Entity
#Table(name = "component")
public class Component {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer compId;
#Column(nullable = false, unique = true)
#NotEmpty
private String compName;
#ManyToMany(mappedBy = "component")
private List < Role > roles;
I am getting the following error, Please suggest the mistake
Caused by: org.hibernate.AnnotationException: mappedBy reference an
unknown target entity property:
net.springboot.helloworldapp.bean.Role.component in
net.springboot.helloworldapp.bean.Component.roles at
org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:785)
There is a typo. component should be components.
#ManyToMany(mappedBy = "components") // <- should be components
private List < Role > roles;

foreign key not getting inserted when hibernate one to one mapping is used

I have two entites as follows
user entity
#Entity
#Table(name = "user")
#Getter
#Setter
public class UserEntity{
#Id
#GeneratedValue(strategy = GeneratedType.IDENTITY)
#Column(name = "user_id")
private Long userId;
#Column(name = "user_name")
private String name;
#OneToOne(Cascade=CascadeType.ALL, mappedBy="user")
private UserAddressEntity addressEntity;
}
user address entity
#Entity
#Table(name = "user_address")
#Getter
#Setter
public class UserAddressEntity{
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "user_id")
private Long userId;
#Column(name = "address")
private String address;
#OneToOne
#JoinColumn(name = "user_id", nullable = false, referencedColumnName = "user_id")
private UserEntity user;
}
I am saving user entity as follows in service class
#Service
public class UserService{
#Autowired
private UserRepository userRepository;
public void saveUser(){
UserEntity userEntity=new UserEntity();
UserAddressEntity userAddressEntity=new UserAddressEntity();
//logic here
userEntity.setAddressEntity(userAddressEntity);
userRepository.save(userEntity);
}
}
After saving entity user_id column is not being saved in user_address table. It's value is saved as null.I can't seem to find where the issue is.
EDIT:
I have added following to entities after answer referred in comments but I am getting this error
Infinite recursion (StackOverflowError)
#Entity
#Table(name = "user")
#Getter
#Setter
public class UserEntity{
#Id
#GeneratedValue(strategy = GeneratedType.IDENTITY)
#Column(name = "user_id")
private Long userId;
#Column(name = "user_name")
private String name;
#OneToOne(Cascade=CascadeType.ALL, mappedBy="user")
private UserAddressEntity addressEntity;
//added this
public void setAddressEntity(UserAddressEntity addressEntity){
if (!addressEntity.equals(this.addressEntity)){
this.addressEntity=addressEntity;
addressEntity.setUser(this);
}
}
#Entity
#Table(name = "user_address")
#Getter
#Setter
public class UserAddressEntity{
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "user_id")
private Long userId;
#Column(name = "address")
private String address;
#OneToOne
#JoinColumn(name = "user_id", nullable = false, referencedColumnName = "user_id")
private UserEntity user;
//added this
public void setUser(UserEntity user){
if (!user.equals(this.user){
this.user=user;
}
}
}
You need to set the relationship correctly in UserService.saveUser():
userEntity.setAddressEntity(userAddressEntity);
userAddressEntity.setUser(userEntity);
Also, use regular getters/setters, no need to add logic there.
The recommended/best way to map a #OneToOne is to use #MapsId. With that approach, you don’t need at all a bidirectional association.
I would advise you to take look at link below, there you have answer to your question with example how to save and map between objects.
https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/

Exception trying convert UUID attribute (foreign key) to Entity object

I am developing a spring-boot application (jpa...etc), and I am stuck in one problem. I am using the UUID attribute for the primary keys. When I try to create object as foreign key, the jpa can't cast correctly to my object.
I tried to use a AttributeConverter, but jpa does not call it.
My UserEntity
#Entity(name = "User")
#Table(name = "USR")
#EntityListeners(UserPersistListener.class)
#EqualsAndHashCode
public class UserEntity {
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
#Column(name = "ID", updatable = false)
#Getter
#Setter
private String id;
#Column(name = "LOGIN", updatable = false)
#Getter
#Setter
private String login;
#Column(name = "PASS")
#Getter
#Setter
private String pass;
#Enumerated(EnumType.STRING)
#Column(name = "ROLE")
#Getter
#Setter
private Role role;
}
My other Entity Person using UserEntity (foreign key)
#Entity(name = "Person")
#Table(name = "PERSON")
#EqualsAndHashCode
public class PersonEntity {
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
#Column(name = "ID", updatable = false)
#Getter
#Setter
private String id;
#Column(name = "NAME")
#Getter
#Setter
private String name;
#Column(name = "SUBSCRIPTION")
#Getter
#Setter
private Long subscription;
#Enumerated(EnumType.STRING)
#Column(name = "SUBSCRIPTION_TYPE")
#Getter
#Setter
private SubscriptionType subscriptionType;
#Column(name = "PHONE1")
#Getter
#Setter
private Long phone1;
#Column(name = "PHONE2")
#Getter
#Setter
private Long phone2;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "CREATED_BY", updatable = false)
#Getter
#Setter
private UserEntity createdBy;
#Convert(converter = LocalDateAttributeConverter.class)
#Column(name = "CREATION_DATE")
#Getter
#Setter
private LocalDateTime creationDate;
}
Exception
org.springframework.data.domain.PageImpl["content"]->java.util.Collections$UnmodifiableRandomAccessList[0]->br.com.orangesun.entity.person.PersonEntity["createdBy"]->br.com.orangesun.entity.user.UserEntity_$$_jvst424_1["id"])
2019-06-18 00:52:55.163 WARN 15432 --- [nio-8099-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42883
2019-06-18 00:52:55.164 ERROR 15432 --- [nio-8099-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: operator does not exist: uuid = character varying
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
Edit
My database definition
| Field Name | Type |
|-----------------------------|
| id | uuid |
| name | varchar |
| subscription | int8 |
| subscription_type | varchar |
| created_by | uuid |
| creation_date | instant |
| phone1 | int8 |
| phone2 | int8 |
|-----------------------------|
EDIT 2
Other details about same error
java.lang.IllegalArgumentException: Provided id of the wrong type for class br.com.orangesun.entity.person.PersonEntity. Expected: class java.lang.String, got class java.util.UUID
Try to use UUID type instead of String for 'id' fields, because UUID is a binary format, not character based, so databases use special type for UUID fields.
Update your PersonEntity class as below,
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "CREATED_BY", referencedColumnName = "ID”, updatable = false)
#Getter
#Setter
private UserEntity createdBy;
Add referencedColumnName to your #joinColumn
UUID in Postgres is automatically converted for you into UUID datatype. You must change your id datatype from String to UUID and everything will work as expected.
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
#Column(name = "ID", updatable = false)
#Getter
#Setter
private UUID id;
Use UUID instead of String.
Moreover, replace
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "CREATED_BY", updatable = false)
by
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "CREATED_BY", referencedColumnName = "ID", updatable = false)
It gives:
The UserEntity:
#Entity(name = "User")
#Table(name = "USR")
#EntityListeners(UserPersistListener.class)
#EqualsAndHashCode
public class UserEntity {
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
#Column(name = "ID", updatable = false)
#Getter
#Setter
private UUID id;
#Column(name = "LOGIN", updatable = false)
#Getter
#Setter
private String login;
#Column(name = "PASS")
#Getter
#Setter
private String pass;
#Enumerated(EnumType.STRING)
#Column(name = "ROLE")
#Getter
#Setter
private Role role;
}
The other Entity Person using UserEntity (foreign key)
#Entity(name = "Person")
#Table(name = "PERSON")
#EqualsAndHashCode
public class PersonEntity {
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
#Column(name = "ID", updatable = false)
#Getter
#Setter
private UUID id;
#Column(name = "NAME")
#Getter
#Setter
private String name;
#Column(name = "SUBSCRIPTION")
#Getter
#Setter
private Long subscription;
#Enumerated(EnumType.STRING)
#Column(name = "SUBSCRIPTION_TYPE")
#Getter
#Setter
private SubscriptionType subscriptionType;
#Column(name = "PHONE1")
#Getter
#Setter
private Long phone1;
#Column(name = "PHONE2")
#Getter
#Setter
private Long phone2;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "CREATED_BY", referencedColumnName = "ID", updatable = false)
#Getter
#Setter
private UserEntity createdBy;
#Convert(converter = LocalDateAttributeConverter.class)
#Column(name = "CREATION_DATE")
#Getter
#Setter
private LocalDateTime creationDate;
}
as per OP gmrosa's own prior edit to the question.

MappedBy reference an unknown target entity

I design a system of tables in the database for the film service. So far I have designed them in this way.
#Entity
#Table(name = "movies")
#Data
public class MovieEntity {
#Id
#Column(unique = true, updatable = false)
#GeneratedValue
private Long id;
#OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
private Set<MovieDescription> description;
}
#Entity
#Table(name = "movies_info")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "type")
public abstract class MovieInfo {
#Id
#Column(unique = true, updatable = false)
#GeneratedValue
private Long id;
#ManyToOne
public MovieEntity movie;
}
#Entity
#DiscriminatorValue(value = EditType.Values.DESCRIPTION)
public class MovieDescription extends MovieInfo {
private String description;
private String language;
}
When compiling, it sends me a mistake
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.core.jpa.entity.MovieDescription.movie in com.core.jpa.entity.MovieEntity.description
Something related to MovieEnity mapping, but I don't know what it is all about.
use targetEntity attribute to target the super class field that you want to map with.
#Entity
#Table(name = "movies")
#Data
public class MovieEntity {
#Id
#Column(unique = true, updatable = false)
#GeneratedValue
private Long id;
#OneToMany(mappedBy = "movie", cascade = CascadeType.ALL, targetEntity= MovieInfo.class)
private Set<MovieDescription> description;
}
More detail: one to many mapping to a property of superclass

Categories