I'm trying to use a foreign key in Hibernate/Spring Boot with the #OneToMany and #ManyToOne annotations, but I keep getting this error:
java.sql.SQLException: Field 'note_id' doesn't have a default value
My code:
Note.java
#Entity
#Table(name = "notes")
#EntityListeners(AuditingEntityListener.class)
public class Note {
public Note() {
}
public Note(String name, String content) {
this.name = name;
this.content = content;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "note_id")
private Integer id;
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#NotBlank
private String name;
#NotBlank
#Column(columnDefinition="LONGTEXT")
private String content;
User.java
#Entity
#Table(name = "user")
#EntityListeners(AuditingEntityListener.class)
public class User implements Serializable {
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private Integer id;
#OneToMany(mappedBy = "user", cascade = ALL)
private Set<Note> notes;
#NotEmpty
#Column(nullable = false, unique = true)
private String username;
#NotEmpty
private String password;
The error occurs whenever I try to create a note.
Thanks in advance!
Related
I want to create a Person with an Address, each of them are an entity. My Entities seem to work, the part where i begin to struggle is on how to create a Person using the constructor where i also have to put in the Address.
personRepository.save(new Person(new Name("Test","Test"),new Adress("Street","Number","PLZ","Town"),LocalDate.parse("2000-01-01"),"email#email.com","911");
This sadly does not work so my question is how can i create a Person object with the Address.
I'm also wondering how i would add the address if i already got the address in my Address repository, is there a way to get the address or use the adress ID?
adresseRepository.save(new Adresse("Street","Number","PLZ","Town"));
Here's the code for both of the shortend.
Person:
#Entity
#Table(name = "Person")
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PersonID")
private Long personID;
#Column(name = "FullName")
#Convert(converter = NameConverter.class)
private Name fullName;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="AdresseID")
private Adresse adresse;
#Column(name = "Geburtsdatum")
private LocalDate geburtsdatum;
#Column(name = "EMail")
private String email;
#Column(name = "Telefonnummer")
private String telefonnummer;
private Person() {}
public Person(Name fullName, Adresse adresse, LocalDate geburtsdatum, String email, String telefonnummer) {
this.fullName = fullName;
this.adresse = adresse;
this.geburtsdatum = geburtsdatum;
this.email = email;
this.telefonnummer = telefonnummer;
}
}
Address:
#Entity
#Table(name = "Adresse")
public class Adresse {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "AdresseID")
private Long adresseID;
#Column(name = "Strasse")
private String strasse;
#Column(name = "Hausnummer")
private String hausnummer;
#Column(name = "PLZ")
private String plz;
#Column(name = "Ort")
private String ort;
protected Adresse() {}
public Adresse(String strasse, String hausnummer, String plz, String ort) {
this.strasse = strasse;
this.hausnummer = hausnummer;
this.plz = plz;
this.ort = ort;
}
}
Ralationships are created in hibernate like this:
#Entity
#Table(name="CART")
public class Cart {
//...
#OneToMany(mappedBy="cart")
private Set<Item> items;
// getters and setters
}
Please note that the #OneToMany annotation is used to define the property in Item class that will be used to map the mappedBy variable. That is why we have a property named “cart” in the Item class:
#Entity
#Table(name="ITEMS")
public class Item {
//...
#ManyToOne
#JoinColumn(name="cart_id", nullable=false)
private Cart cart;
public Item() {}
// getters and setters
}
Soin your case you just have to add
#Entity
#Table(name = "address")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
//...
#OneToOne(mappedBy = "address")
private User user;
something lilke this to your Adress Table.
Because one Adress also have one user.
For more information visit this site
I am having a faq entity as below. Here createdBy field is having a manyToOne relationship with the user entity. Below joinColumns shows the association.
In the User entity, i have OneToMany relationship with UserRoles and UsersUnit which is EAGER load for User and not for faq. So i added #JsonIgnoreProperties
for UsersUnit and UsersRole and the corresponding User entity is shown below.
#Entity
#Table(name = "FAQ", catalog="abc")
public class Faq implements Serializable {
public Faq() {
super();
}
#Column(name = "CREATE_DATE")
private Timestamp createDate;
#Where(clause = "DELETE_DATE is null")
#Column(name = "DELETE_DATE")
private Timestamp deleteDate;
#Column(name = "DELETED_BY")
private BigDecimal deletedBy;
#Column(name = "DOC_BLOB", nullable = false)
#JsonIgnore
private byte[] docBlob;
#Column(name = "DOC_NAME", nullable = false, length = 100)
private String docName;
#Id
private BigDecimal id;
#Column(name = "ORDER_BY")
private BigDecimal orderBy;
#Column(name = "UPDATE_DATE")
private Timestamp updateDate;
#Column(name = "UPDATED_BY")
private BigDecimal updatedBy;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumns({
#JoinColumn(name="created_by", referencedColumnName="id")
})
private User faqCreatedBy;
}
User entity:
#Entity
#Table(name = "USERS", catalog="abc")
#JsonInclude(Include.NON_NULL)
public class User extends EntityLog{
private BigDecimal id;
private BigDecimal edipi;
private String firstname;
private String lastname;
private String email;
..///
private Set<UsersRoles> userRoles;
private Set<UsersUnit> usersUnit;
#Id
#Column(name="id")
public BigDecimal getId() {
return id;
}
...///
#Column
#JsonIgnoreProperties({ "faqCreatedBy" })
#OneToMany(fetch = FetchType.EAGER,mappedBy = "user",cascade = {CascadeType.ALL})
#JsonManagedReference
public Set<UsersRoles> getUserRoles() {
return userRoles;
}
...///
#Column
#JsonIgnoreProperties({ "faqCreatedBy" })
#OneToMany(fetch = FetchType.EAGER,mappedBy = "user",cascade = {CascadeType.ALL})
#JsonManagedReference
public Set<UsersUnit> getUsersUnit() {
return usersUnit;
}
////...
}
With this change I am expecting the faq to load with User entity but I am not execting UsersRoles and UsersUnit to load.
But that is not what i see. When faq loads it loads User and UsersRoles and UsersUnit. I am using Spring JPA fyi. Any leads what is wrong ? Appreciate any inputs.
I'm having this error
Error accessing field [private java.lang.Integer
fearx.projects.animal.finder.api.entity.LoginEntity.id] by reflection
for persistent property
[fearx.projects.animal.finder.api.entity.LoginEntity#id] : 2; nested
exception is
org.hibernate.property.access.spi.PropertyAccessException: Error
accessing field [private java.lang.Integer
fearx.projects.animal.finder.api.entity.LoginEntity.id] by reflection
for persistent property
[fearx.projects.animal.finder.api.entity.LoginEntity#id] : 2
While I try to do this:
public void registerUser(OwnerEntity body) {
ownerRepository.save(body);
loginRepository.save(new LoginEntity(body.getEmail(), body.getPassword()));
LoginEntity loginEntity = loginRepository.findByEmail(body.getEmail());
OwnerEntity ownerEntity = ownerRepository.findByEmail(body.getEmail());
ownerLoginRepository.save(new OwnerLoginEntity(loginEntity.getId(),ownerEntity.getId()));
}
My entitys:
#Entity(name = "owner_login")
#Data
public class OwnerLoginEntity {
#Id
#GeneratedValue
private Integer id;
#ManyToOne(targetEntity = LoginEntity.class)
#JoinColumn(name = "id_login", referencedColumnName = "id")
private Integer login;
#ManyToOne(targetEntity = OwnerEntity.class)
#JoinColumn(name = "id_owner", referencedColumnName = "id")
private Integer owner;
public OwnerLoginEntity(Integer login, Integer owner) {
this.login = login;
this.owner = owner;
}
}
public class OwnerEntity {
#Id
#GeneratedValue
private Integer id;
#Column
private String name;
#Column
private String email;
#Column
private String phone;
#Column
private String password;
#ManyToOne(targetEntity = LostPetEntity.class)
#JoinColumn(name = "id_pet", referencedColumnName = "id")
private Integer id_pet;
}
#Entity(name = "login")
#Data
public class LoginEntity {
#Id
#GeneratedValue
private Integer id;
#Column(unique = true, nullable = false)
private String email;
#Column
private String password;
public LoginEntity(String email, String password) {
this.email = email;
this.password = password;
}
public LoginEntity() {
}
}
O don't know what database you have, but try to change the approach of GeneratedValue like this:
#Entity(name = "owner_login")
#Data
public class OwnerLoginEntity {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#ManyToOne
private LoginEntity login;
#ManyToOne
private OwnerEntity owner;
public OwnerLoginEntity(LoginEntity login, OwnerEntity owner) {
this.login = login;
this.owner = owner;
}
}
Then you can call ownerLoginRepository.save(new OwnerLoginEntity(loginEntity, ownerEntity));
I created objects User and Message, and now I want, that message's id will be associated with the user id. How can I do it with annotations or with something else?
Table User
Table Messge
Message class
#Entity
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String text;
private String tag;
}
User class
#Entity
#Table(name = "usr")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
private boolean active;
#ElementCollection(targetClass = Role.class , fetch = FetchType.LAZY)
#CollectionTable(name = "user_role" , joinColumns = #JoinColumn(name = "user_id"))
#Enumerated(EnumType.STRING)
private Set<Role> roles;
}
you can try this:
Message class:
#Entity
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String text;
private String tag;
#ManyToOne
#JoinColumn(name = "user_id")
private User userId;
}
user class:
#Entity
#Table(name = "usr")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
private boolean active;
#ElementCollection(targetClass = Role.class , fetch = FetchType.LAZY)
#CollectionTable(name = "user_role" , joinColumns = #JoinColumn(name = "user_id"))
#Enumerated(EnumType.STRING)
private Set<Role> roles;
#OneToMany(mappedBy = "user")
#JsonBackReference
private set<Message> messages;
}
I'm making an application that use a Rest Api to handle the communication between front and database.
Spring is used for the Java Api and Postgres as database.
The point is that I need a ternary relationship between three table. I explain myself, I have three table :
- user
- role
- project
Every user have a specific role depending on the project.
When I select a Project (in front), I need to display all the participants with their respective project.
Those are my classes :
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String email;
#NotNull
#Column(name = "last_name")
private String lastName;
#NotNull
#Column(name = "first_name")
private String firstName;
#NotNull
private String password;
private String image;
#Entity
#Table(name = "projects")
public class Project {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String name;
#NotNull
private Long version;
#NotNull
private Date date;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "user_profile_project", joinColumns = #JoinColumn(name = "project_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"))
private List<User> participants;
#Entity
#Table(name = "profiles")
public class Profile {
private Long id;
private String name;
private Set<Permission> permissions = new HashSet<Permission>(0);
public Profile(){}
public Profile(String name) {
this.name = name;
}
public Profile(String name, Set<Permission> permissions) {
this.name = name;
this.permissions = permissions;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "name", nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}