I have class User:
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
private String name;
private String password;
#ManyToMany
#JoinTable
private List<Role> roles;
}
Class Owner inherits from User
#Entity
public class Owner extends User {
private String pesel;
private String adress;
#OneToMany(cascade={CascadeType.PERSIST, CascadeType.REMOVE})
private List<Pet> pets;
}
and Owner had Pet
public class Pet {
#Id
#GeneratedValue
private Integer id;
private String name;
private String weight;
#ManyToOne
private Owner owner;
}
Why when starting the application gets the error:
org.springframework.data.mapping.PropertyReferenceException: No
property user found for type Pet!
--EDIT
First I have version, which was as follows:
now I try to share User instance to a doctor and the owner of the animal
The problem is that I do not know whether I am doing the mapping , and therefore wanted to ask whether it must look like
--edit2
I've simplified the scheme just a bit to better illustrate what happens
--edit3
Currently my Object's was presented:
#Entity
public class Pet {
#Id
#GeneratedValue
private Integer id;
private String name;
private String weight;
}
User
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
private String name;
private String password;
#ManyToMany
#JoinTable(name="user_roles")
private List<Role> roles;
}
PetOwner
#Entity
public class PetOwner extends User {
private String pesel;
private String adress;
#OneToMany(mappedBy="petOwner")
private List<Pet> pets;
}
I replace
#ManyToOne
private PetOwner petOwner;
for
#ManyToOne
private Owner petOwner;
and it works. Do you have a PetOwner class?
Also provide the log error to get more information about it
Related
I have entities like below:
public class UserName {
#Id
private Long id;
private String name;
#OneToMany(mappedBy = "userName")
private User;
}
public class UserAge {
#Id
private Long id;
private int age;
#OneToMany(mappedBy = "userAge")
private User;
}
public class User {
#Id
private Long id;
#ManyToOne
private UserName userName;
#ManyToOne
private UserAge userAge;
}
When I search users whose name is the one with UserName.id = 100,
how can I do that?
I found an almost same question here, however it didn't work like below
public interface UserRepository extends JpaRepository<User, Long>{
Long countByUserNameId(Long id);
}
I am new to hibernate and I am trying to implement a basic application that uses this schema (it does not follow the notation I just use it for clarity)
Here is the my classes
#Entity
#Table(name = "race")
public class Race {
#Id
#GeneratedValue
private UUID id;
private String name;
}
#Entity
#Table(name="np_character")
public class NPCharacter {
#Id
#GeneratedValue
private UUID id;
#OneToOne
private Race race;
private String name;
private int age;
}
#Entity
#Table(name="main_female_character")
public class MainFemaleCharacter {
#Id
#GeneratedValue
private UUID id;
#OneToOne
private Race race;
private String name;
private int age;
}
#Entity
#Table(name="copulation_registry")
public class CopulationRegistry {
// ??
private NPCharacter npCharacter;
// ??
private MainFemaleCharacter femCharacter;
private int times;
}
But I ran into the problem with copulation_registry class. I used everywhere OneToOne annotation, instead of using references to keys. But what I should do here? Pairs of id_femPlayer and id_npCharacter are unique.
Should I use EmbeddedId annotation or is it possible somehow to use association annotations to represent the same relation?
You can annotate class CopulationRegistry with #IdClass
#Entity
#IdClass(CopulationRegistryKey.class)
#Table(name="copulation_registry")
public class CopulationRegistry {
#Id
private NPCharacter npCharacter;
#Id
private MainFemaleCharacter femCharacter;
private int times;
}
public class CopulationRegistryKey{
private NPCharacter npCharacter;
private MainFemaleCharacter femCharacter;
}
So lets say I have User object like this
#Entity
public class User {
#Id
#GeneratedValue
private long id;
private String name;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "address", referencedColumnName = "id")
private Address address;
}
#Entity
public class Address {
#Id
#GeneratedValue
private long id;
private String city;
private String country;
}
Now I don't want to write validation annotations in entities. What I would like to do is validate User in #RestController like this
#RestController
public class InvoiceController {
#RequestMapping(value="/users/add", method = RequestMethod.POST)
public Invoice addInvoice(#Validated #RequestBody ValidUser user) {
... do stuff
}
}
The validation annotations would be in ValidUser being like this.
public class ValidUser extends User {
#NotNull
private String name;
#Valid
private Address address;
}
public class ValidAddress extends Address{
#NotNull
private String city;
#NotNull
private String country;
}
The validation works when I remove the address field from the ValidUser but not when it is there. How can I make address validation also work?
I am trying to set up our database in our project. But I get some errors, when I try to use #ManyToOne and#OneToMany on a #MappedSuperclass Entity:
#MappedSuperclass
public abstract class Person extends Model{
//public abstract class Person {
// ATTRIBUTES
#Column(columnDefinition = "varchar(20) not null")
private String firstName;
#Column(columnDefinition = "varchar(20) not null")
private String lastName;
#Column(columnDefinition = "varchar(20) not null")
private String password;
#Column(columnDefinition = "varchar(50) not null")
private String eMail;
#Column(columnDefinition = "varchar(8) not null")
private String svn;
private static int staticId = 0; // Identifier, staticId is unique.
#Id
#Column(columnDefinition = "integer not null")
private int id;
#Column(columnDefinition = "integer")
private int age;
#Column(columnDefinition = "varchar(10)")
private String telephoneNumber;
#Column(columnDefinition = "decimal(10,2)")
private double salary;
#Column(columnDefinition = "boolean")
private boolean allowedOvertime;
//#OneToMany(mappedBy = "person")
private List<TimeEntryMonth> listTimeEntryMonth;
#OneToMany(mappedBy = "person")
private List<Vacation> listVacation;
#OneToMany(mappedBy = "person")
private List<SickLeave> listSickLeave;
One of the classes who extends from Person:
#Entity
public class Employee extends Person {
// ATTRIBUTES
private String position;
private Boss boss;
And one of the #OneToMany relations:
public class SickLeave extends Model {
/* ATTRIBUTES */
#Id
private int id;
#ManyToOne
private Person person;
private int personIdSL;
private String reason;
If I compile my whole Project without the #ManyToOne and #OneToMany, it will work fine. But with the it will lead into som errors:
Error injecting constructor, java.lang.RuntimeException: Error reading
annotations for models.SickLeave
I tried to delete the abstract and replaced #MappedSuperclass with #Entity and the project works. So I think that I cant have #OneToMany and #ManyToOne relations on a #MappedSuperclass, But I dont want to refactor my whole project
Is there any (easier) way to handle such issues?
Thank you.
Person is not an Entity, so you can't use OneToMany to it. You will need to make Person an Entity or point to Employee, which seems to make more sense to me.
I can't make my foreign keys auto generate using hibernate and jpa with annotations. Everything seems ok, The entries are saved in database. All the date come from one form which, when submited creates an User object with ModelAttribute and then saves it in Database.
Here are my beans. Anything else i should add ?
#Entity
#Table(name="adress")
public class Adress implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="adress_id")
private Integer adressId;
#NotBlank(message="The city must be completed")
#Column(name="city")
#Size(min=5,max=30)
private String city;
#NotBlank(message="The street must be completed")
#Column(name="street")
#Size(min=5,max=30)
private String street;
#NotNull(message="The street number must be completed")
#NumberFormat
#Column(name="street_no")
private Integer streetNo;
#OneToOne
#JoinColumn(name="user_id")
private User user;}
and the other one:
#Entity
#Table(name="users")
public class User implements Serializable {
#Id
#Column(name="user_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer userId;
#NotBlank(message="Username can't be blank")
#Size(min=5,max=30)
#Column(name="username")
private String username;
#NotBlank(message="Password field can't be blank")
#Size(min=5,max=30)
#Column(name="password")
private String password;
#NumberFormat
#NotNull(message="Age field must not be blank")
#Column(name="age")
private Integer age;
#Column(name="message")
#Size(min=0,max=100)
private String message;
#Column(name="date")
#DateTimeFormat(pattern="dd/mm/yyyy")
private Date dateCreated;
#OneToOne(mappedBy="user",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private Adress adress;
+getters and setters for them
public void save(T entity){
sessionFactory.getCurrentSession().save(entity);
}
If I understand you correctly and you're trying to get Hibernate to set the foreign key on your related record this might help. Try getting rid of mappedBy and instead specify the JoinColumn. This works for me on a one to many:
The order:
#Entity
#Table(name = "`order`")
public class Order implements Serializable {
#Id
#GeneratedValue
private Long id;
// Order columns...
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "order_id")
private Set<Item> items;
}
The item:
#Entity
#Table(name = "item")
public class Item implements Serializable {
#Id
#GeneratedValue
private Long id;
// Item columns...
#ManyToOne(optional = false)
#JoinColumn(name = "order_id", referencedColumnName = "id", nullable = false)
private Order order;
}
in adress class
#OneToOne(mappedBy="adress")
private User user;
and in user class
#OneToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER,optional=false)
#PrimaryKeyJoinColumn
private Adress adress;