i have faced with the problem, that JSON doesn't containe the list of nested objects.
I have 2 classes, one of them is carrying information about auto service, another one containes information about services.
One autoservice can has many services. So, we have the relation - one to many .
AutoService class:
#Entity
#Table(name = "AutoRate")
public class AutoService {
public AutoService() {
}
#Id
#GeneratedValue(generator = "increment")
#GenericGenerator(name = "increment", strategy = "increment")
private long id;
#Column(name = "serviceName", nullable = false)
private String serviceName;
#Column(name = "imageURL", nullable = false)
private String imageURL;
#Column(name = "mapCoordinate", nullable = false)
private String mapCoordinate;
#Column(name = "websiteURL", nullable = false)
private String websiteURL;
#Column(name = "phoneNumber", nullable = false)
private String phoneNumber;
#OneToMany(fetch = FetchType.EAGER)
#JoinColumn(name = "autoServiceId")
private List<Service> services;
public long getId() {
return id;
}
public String getServiceName() {
return serviceName;
}
public String getImageURL() {
return imageURL;
}
public String getMapCoordinate() {
return mapCoordinate;
}
public String getWebsiteURL() {
return websiteURL;
}
public String getPhoneNumber() {
return phoneNumber;
}
}
Service class:
#Entity
#Table(name = "Service")
public class Service {
public Service() {
}
#Id
#GeneratedValue(generator = "increment")
#GenericGenerator(name = "increment", strategy = "increment")
#Column(name = "serviceId", unique = true, nullable = false)
private long serviceId;
#Column(name = "serviceName", nullable = false)
private String serviceName;
#Column(name = "category", nullable = false)
private String category;
#Column(name = "price", nullable = false)
private int price;
#Column(name = "autoServiceId", nullable = false)
private long autoServiceId;
public long getId() {
return serviceId;
}
public String getCategory() {
return category;
}
public int getPrice() {
return price;
}
public String getServiceName() {
return serviceName;
}
public long getAutoServiceId() {
return autoServiceId;
}
}
Also i am using the JpaRepository to get objects from db:
public interface AutoRateRepository extends JpaRepository<AutoService, Long> {
}
Here is Controller class:
#RestController
#RequestMapping("/directory")
public class ServiceController {
#Autowired
private AutoRateService dataBaseService;
#RequestMapping(value = "/get", method = RequestMethod.GET)
#ResponseBody
public List<AutoService> getData(){
List<AutoService> dataList = dataBaseService.getAll();
return dataList;
}
}
But then when i am trying to get JSON object i am getting next:
[
{
"id": 1,
"serviceName": "SpeedyName",
"imageURL": "Url for speedy",
"mapCoordinate": "123123 44121 ",
"websiteURL": "speedy.com",
"phoneNumber": "1231251"
},
{
"id": 2,
"serviceName": "Другой сервис",
"imageURL": "Урл для второго сервиса",
"mapCoordinate": "123 12фывфы",
"websiteURL": "другойсервис.ком",
"phoneNumber": "12312333"
}
]
There is not lists of nested objects from database ( List<Services>
Can you help me to resolve this problem ?
I was told that i had missed the #JsonManagedReference annotation, but it didn't helped me (
As specified in the comments, you're missing a getServices() method in the AutoService entity exposing the collection for serialization.
As a side note, be weary if your Service entity has a back reference to the parent AutoService. If it does, you'll need to make sure your JSON framework knows how to handle cyclic loops or you will need to trigger ignoring the back reference when you serialize the AutoService instances to avoid a stack overflow.
Related
Im learning, and so far i created many to many bidirectional database - user can create many groups and group can have many users - and i cannot find a way for my GroupsController Post mapping to work, from my understanding, it requires to get firstly Users id, in order to set the right relationship in Join table for Group, because the relationship should be set only when user create/join group, not when user create sign up procedure. Postman throws 500 and intelliJ:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "java.lang.Long.longValue()" because the return value of "com.ilze.highlight.entity.Groups.getId()" is null] with root cause
java.lang.NullPointerException: Cannot invoke "java.lang.Long.longValue()" because the return value of "com.ilze.highlight.entity.Groups.getId()" is null
I use lombok - #Data, #Getter, therefore getId() should be available for use from Group class. My GroupsController with POST mapping when user decides to create a new group:
#RestController
#RequestMapping("api/groups") // pre-path
public class GroupsController{
#Autowired
private GroupsService groupsService;
#Autowired
private UserService userService;
#Autowired
private final GroupsRepository groupsRepository;
#Autowired
private UserRepository userRepository;
public GroupsController(GroupsRepository groupsRepository) {
this.groupsRepository = groupsRepository;
}
#GetMapping("/all-groups")
public List<Groups> getGroups(){
return (List<Groups>) groupsRepository.findAll();
}
#PostMapping("/user/{usersId}/create-group")
public ResponseEntity<Groups> createGroup(#PathVariable(value = "usersId") Long usersId, #RequestBody Groups groupRequest){
Groups group = userRepository.findById(usersId).map(users -> {
long groupsId = groupRequest.getId();
// add and create new group
users.addGroup(groupRequest);
return groupsRepository.save(groupRequest);
}).orElseThrow(() -> new ResourceNotFoundException("Not found user with id = " + usersId));
return new ResponseEntity<>(group, HttpStatus.CREATED);
}
}
Group database class:
#Data
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Table(name = "group_collection")
public class Groups {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name ="group_name", unique = true, nullable = false, length = 20)
private String groupName;
#Column(name = "size", nullable = false)
private int size;
#Column(name = "strict", nullable = false)
private boolean strict;
#Column(name = "open", nullable = false)
private boolean open;
#Column(name ="description", length = 300)
private String description;
#Column(name = "create_time", nullable = false)
private LocalDateTime createTime;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH
},
mappedBy = "groups")
#JsonIgnore
private Set<User> users = new HashSet<>();
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
And Users class for database:
#Data
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "username", unique = true, nullable = false, length = 100)
private String username;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "create_time", nullable = false)
private LocalDateTime createTime;
#Enumerated(EnumType.STRING)
#Column(name = "role", nullable = false)
private Role role;
#Transient
private String accessToken;
#Transient
private String refreshToken;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH
})
#JoinTable(name = "groups_x_user",
joinColumns = { #JoinColumn(name = "users_id") },
inverseJoinColumns = {#JoinColumn(name = "groups_id")})
private Set<Groups> groups = new HashSet<>();
public void addGroup(Groups group) {
this.groups.add(group);
group.getUsers().add(this);
}
public void removeGroup(long id){
Groups group = this.groups.stream().filter(g ->
g.getId() == id).findFirst().orElse(null);
if(group != null){
this.groups.remove(group);
group.getUsers().remove(this);
}
}
For reference my GroupsService implementation:
#Service
public class GroupsServiceImpl implements GroupsService{
private final GroupsRepository groupsRepository;
public GroupsServiceImpl(GroupsRepository groupsRepository) {
this.groupsRepository = groupsRepository;
}
#Override
public Groups saveGroup(Groups group) {
group.setCreateTime(LocalDateTime.now());
return groupsRepository.save(group);
}
#Override
public Optional<Groups> findByGroupName(String groupName) {
return groupsRepository.findByGroupName(groupName);
}
}
You need to persist the object from request. And since you have Many-2-Many relation, you can insert related object from both sides. In your case: just add existing user to the newly created group
The method will look something like that:
#PostMapping("/user/{usersId}/groups")
public ResponseEntity<Groups> createGroup(#PathVariable(value = "usersId") Long usersId, #RequestBody Groups groupRequest) {
Groups createdGroup = userRepository.findById(usersId)
.map(user -> {
groupRequest.setId(null); // ID for new entry will be generated by entity framework, prevent override from outside
groupRequest.getUsers().add(user); // add relation
return groupsRepository.save(groupRequest);
}).orElseThrow(() -> new ResourceNotFoundException("Not found user with id = " + usersId));
return new ResponseEntity<>(createdGroup, HttpStatus.CREATED);
}
I have a simple spring-boot app where Product needs to be stored and conversion between DTO and Entity needs to happen. I am using the ModelMapper dependency. User can attach a ProductCategory to the Product or leave it empty. Similarly Product can have multiple ReplaceNumber or empty. If I dont attach category it gives error. If I attach category it saves the product with the attached category. If I leave the replaceNumbers array empty it saves. If I fill it it gives errors. Errors are described below.
ProductCategory
#Entity
#Table(name = "product_categories")
public class ProductCategory
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank
#Column(name = "name", nullable = false)
#Size(max = 20)
private String name;
public ProductCategory()
{
}
public ProductCategory(String name)
{
this.name = name;
}
}
ReplaceNumber
#Entity
#Table(name = "replace_numbers")
public class ReplaceNumber
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank
#Size(max = 20)
private String partNumber;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "product_id", nullable = false)
private Product product;
public ReplaceNumber()
{
}
public ReplaceNumber(String partNumber)
{
this.partNumber = partNumber;
}
}
Product
#Entity
#Table(name = "products", indexes = {#Index(name= "part_number_index", columnList = "part_number", unique = true)})
public class Product
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank
#Column(name = "part_number", nullable = false)
#Size(max = 20)
private String partNumber;
#NotBlank
#Size(max = 255)
private String description;
#OneToMany(
mappedBy = "product",
cascade = CascadeType.ALL,
fetch = FetchType.EAGER,
orphanRemoval = true
)
#Fetch(FetchMode.SELECT)
private List<ReplaceNumber> replaceNumbers = new ArrayList<>();
#ManyToOne
#JoinColumn(name = "product_category_id", referencedColumnName = "id")
private ProductCategory category;
}
Following are the DTO Classes that need to be converted.
ReplaceNumberRequest
public class ReplaceNumberRequest
{
#NotBlank
#Size(max = 20)
private String partNumber;
public String getPartNumber()
{
return partNumber;
}
public void setPartNumber(String partNumber)
{
this.partNumber = partNumber;
}
}
ProductCategoryResponse
public class ProductCategoryResponse
{
private Long id;
private String name;
public ProductCategoryResponse()
{
}
public ProductCategoryResponse(String name)
{
this.name = name;
}
}
ProductRequest
public class ProductRequest
{
#NotBlank
#Size(max = 20)
private String partNumber;
#NotBlank
#Size(max = 255)
private String description;
private List<ReplaceNumberRequest> replaceNumbers = new ArrayList<>();
private ProductCategoryResponse category;
}
ProductService
#Service
public class ProductService
{
#Autowired
ProductRepository productRepository;
public Product create(ProductRequest productRequest)
{
Product product = new Product();
org.modelmapper.ModelMapper modelMapper = new org.modelmapper.ModelMapper();
modelMapper.map(productRequest, product);
return productRepository.save(product);
}
}
If I post the following JSON from Postman
{
"partNumber": "443455783",
"description": "443434",
"replaceNumbers": [],
"category": ""
}
It goes for saving the empty category and produces the following error.
org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : org.walana.GP.model.Product.category -> org.walana.GP.model.ProductCategory; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : org.walana.GP.model.Product.category -> org.walana.GP.model.ProductCategory
If I post the following JSON from Postman
{
"partNumber": "443455783",
"description": "443434",
"replaceNumbers": [
{
"partNumber": "123455"
},
{
"partNumber": "343435"
}
],
"category": {
"id": 1,
"name": "Mounting"
}
}
It gives following error.
could not execute statement; SQL [n/a]; constraint [part_number_index]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
I am confused about how to save entry in db with column's join. I have #Entity bellow
#XmlRootElement
#XmlAccessorType(value = XmlAccessType.FIELD)
#Entity
#Table(name = "psc_users")
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 8885916014620036457L;
#Id
private static final String SEQUENCE_NAME = "psc_users_user_id_seq";
#Id
#GeneratedValue(generator = "UseExistingOrGenerateIdGenerator",
strategy = GenerationType.SEQUENCE)
#GenericGenerator(name = "UseExistingOrGenerateIdGenerator",
strategy = "com.psc.util.UseExistingOrGenerateIdGenerator",
parameters = {
#org.hibernate.annotations.Parameter(name = "sequence", value = SEQUENCE_NAME)
}
)
#Column(name = "USER_ID")
private Long userId;
#Column(name = "DEF", length = 30)
private String def;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DEL_DATE")
private Date delDate;
#Column(name = "DISPLAY_DEF", length = 60)
private String displayDef;
#Column(name = "EMAIL", length = 60)
private String email;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "NAVI_DATE")
private Date naviDate;
#Column(name = "NAVI_USER")
private String naviUser;
#Column(name = "PHONE", length = 30)
private String phone;
#Column(name = "PWD", length = 40)
private String pwd;
//bi-directional many-to-one association to Branch
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "BRNC_BRNC_ID", nullable = false)
private Branch pscBranch;
public Long getBrncBrncId() {
return brncBrncId;
}
public void setBrncBrncId(Long brncBrncId) {
this.brncBrncId = brncBrncId;
}
#Column(name = "BRNC_BRNC_ID", insertable = false, updatable = false)
private Long brncBrncId;
//bi-directional many-to-one association to User
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "CURATOR_USER_ID")
private User pscUser;
public Long getCuratorUserId() {
return curatorUserId;
}
public void setCuratorUserId(Long curatorUserId) {
this.curatorUserId = curatorUserId;
}
#Column(name = "CURATOR_USER_ID", insertable = false, updatable = false)
private Long curatorUserId;
public User() {
}
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getDef() {
return this.def;
}
public void setDef(String def) {
this.def = def;
}
public Date getDelDate() {
return this.delDate;
}
public void setDelDate(Date delDate) {
this.delDate = delDate;
}
public String getDisplayDef() {
return this.displayDef;
}
public void setDisplayDef(String displayDef) {
this.displayDef = displayDef;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getNaviDate() {
return this.naviDate;
}
public void setNaviDate(Date naviDate) {
this.naviDate = naviDate;
}
public String getNaviUser() {
return this.naviUser;
}
public void setNaviUser(String naviUser) {
this.naviUser = naviUser;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPwd() {
return this.pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public Branch getPscBranch() {
return this.pscBranch;
}
public void setPscBranch(Branch pscBranch) {
this.pscBranch = pscBranch;
}
public User getPscUser() {
return this.pscUser;
}
public void setPscUser(User pscUser) {
this.pscUser = pscUser;
}
}
if I save User instance without field pscUser (here null) but there is valid CuratorUserId with correct value I end up in a situation with empty CuratorUserId in db. If you look at code then you will see these bound fields.
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "CURATOR_USER_ID")
private User pscUser;
#Column(name = "CURATOR_USER_ID", insertable = false, updatable = false)
private Long curatorUserId;
code to save user
repositoryUser.save(user);
this i see in debugger
this i see in database after saving my user.
sorry for my stupid question but I come across on a different behavior, there is code in my project which behaves in another manner. I don't want to search actual another user(curator) for saving my user, because of overhead on query
The #Column annotation on the curetorUserId field has properties
insertable=false and updatable=false, which means that its value is ignored during inserts and updates.
You can either change these properties to true (but it can break your application in some other places) or just fill in pscUser field using EntityManager.getReference, which just creates a proxy and doesn't actualy produce a query to the database.
Your mapping should look like the below:
#XmlRootElement
#XmlAccessorType(value = XmlAccessType.FIELD)
#Entity
#Table(name = "psc_users")
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 8885916014620036457L;
#Id
private static final String SEQUENCE_NAME = "psc_users_user_id_seq";
#Id
#GeneratedValue(generator = "UseExistingOrGenerateIdGenerator",
strategy = GenerationType.SEQUENCE)
#GenericGenerator(name = "UseExistingOrGenerateIdGenerator",
strategy = "com.psc.util.UseExistingOrGenerateIdGenerator",
parameters = {
#org.hibernate.annotations.Parameter(name = "sequence", value = SEQUENCE_NAME)
}
)
#Column(name = "USER_ID")
private Long userId;
#Column(name = "DEF", length = 30)
private String def;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DEL_DATE")
private Date delDate;
#Column(name = "DISPLAY_DEF", length = 60)
private String displayDef;
#Column(name = "EMAIL", length = 60)
private String email;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "NAVI_DATE")
private Date naviDate;
#Column(name = "NAVI_USER")
private String naviUser;
#Column(name = "PHONE", length = 30)
private String phone;
#Column(name = "PWD", length = 40)
private String pwd;
//bi-directional many-to-one association to Branch
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "BRNC_BRNC_ID", nullable = false)
private Branch pscBranch;
//bi-directional many-to-one association to User
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "CURATOR_USER_ID")
private User pscUser;
public User() {
}
}
You need to think in terms of objects. The FK will only be set in the database if you set the pscUser reference to an instance of a User. If this is an existing User then you need to set a reference to the existing persistent entity.
Real answer is that I have two points for saving and updating my entity. Please see this Hibernate: Where do insertable = false, updatable = false belong in composite primary key constellations involving foreign keys?
I' m quite knew to Java and currently I am working on a ChatProgramm.
So I want to create a table Messages embedded with the ID (USERNUMBER) of my table Contacts using Injections.
Here' s the class of my Message:
#Embeddable
#Entity(name = "MESSAGE")
public class Message implements Serializable {
#ManyToOne
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "INCOME_MESSANGE", nullable = false)
private String incomingMessage;
#EmbeddedId
#JoinColumn(name = "USERNUMBER", nullable = false)
private Contact contact;
ChatApplicationRemote chatApplicationRemote;
public Message(String ip, String msg) throws IOException {
incomingMessage = msg;
contact = chatApplicationRemote.getcontactByIP(ip.toString());
}
public Message(){
}
public String getIncomingMessage() {
return incomingMessage;
}
public Contact getContact() {
return contact;
}
And here my contacts:
#Entity(name = "CONTACTS")
#Embeddable
public class Contact implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6855140755056337926L;
#Column(name = "NAME", nullable = false)
private String name;
#Column(name = "PRENAME", nullable = false)
private String vorname;
#Column(name = "IP", nullable = false)
private String ip;
#Column(name = "PORT", nullable = false)
private Integer port;
#Id
#OneToMany(mappedBy = "Message.incomingMessage")
#Column(name = "USERNUMBER", nullable = false)
private String usernumber;
public Contact(String usernumber, String name, String vorname, String ip, String port) {
super();
this.usernumber = usernumber;
this.name = name;
this.vorname = vorname;
this.ip = ip;
this.port = Integer.parseInt(port);
}
public Contact(){
}
public String getUsernumber() {
return usernumber;
}
//......
So in my Message, I get two errors:
#ManyToOne throws : Target entity "java.lang.String" is not an Entity
#EmbeddedID throws : de.nts.data.Contact is not mapped as an embeddable
So I googled for a while.. and found something abouta orm.xml which I hadn't have. And even if I create one, #EmbeddedID throws:Embedded ID class should include method definitions for equals() and hashcode() and the orm.xml Attribute "usernumber" has invalid mapping type in this context.
Can anyone please help?
Try
#Entity
public class Message implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name = "INCOME_MESSANGE", nullable = false)
private String incomingMessage;
#ManyToOne
#JoinColumn(name = "USERNUMBER", nullable = false)
private Contact contact;
#Transient
ChatApplicationRemote chatApplicationRemote;
..
}
#Entity
public class Contact implements Serializable {
private static final long serialVersionUID = -6855140755056337926L;
#Column(name = "NAME", nullable = false)
private String name;
#Column(name = "PRENAME", nullable = false)
private String vorname;
#Column(name = "IP", nullable = false)
private String ip;
#Column(name = "PORT", nullable = false)
private Integer port;
#Id
#Column(name = "USERNUMBER", nullable = false)
private String usernumber;
#OneToMany(mappedBy = "incomingMessage")
private LIst<Message> messages;
..
}
maybe as a starting point, but as JB Nizet suggested, start with some simple JPA/Java demos to get the basics first and build up. Your example has many more errors then just what the exception was showing, none of which are solved by just throwing in an ORM.xml.
I'm trying to get the hang of Hibernate.
After getting my project to compile, I've started to convert my classes to be "Hibernate-enabled"
Currently, I'm having 2 classes
1) Person (id, name, firstname, ...)
2) Task (Id, name, description, idOwner)
I would like to have a OneToMany relationship between Person(id) and Task (idOwner)
So when the users gets the List from the Person class, they would get all the tasks linked to that.
After some trying and failing, here's my current code:
Person.java
#Entity
#Table(name = "people", uniqueConstraints = {
#UniqueConstraint(columnNames = "PERSON_ID")
})
public class Person implements Serializable {
private int id;
private String firstName;
private String name;
private String function;
private String email;
private String password;
private RoleEnum role;
private List<Task> lstTasks;
public Person(String firstName, String name, String function) {
this.firstName = firstName;
this.name = name;
this.function = function;
this.email = "";
this.password = "";
this.setRole(RoleEnum.User);
}
// <editor-fold defaultstate="collapsed" desc="Getters">
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "PERSON_ID", unique = true, nullable = false)
public int getId() {
return id;
}
#Column(name = "PERSON_FIRSTNAME", unique = false, nullable = false, length = 30)
public String getFirstName() {
return firstName;
}
#Column(name = "PERSON_NAME", unique = false, nullable = false, length = 30)
public String getName() {
return name;
}
#Column(name = "PERSON_FUNCTION", unique = false, nullable = false, length = 30)
public String getFunction() {
return function;
}
#Column(name = "PERSON_EMAIL", unique = false, nullable = false, length = 30)
public String getEmail() {
return email;
}
#Column(name = "PERSON_PASSWORD", unique = false, nullable = false, length = 30)
public String getPassword() {
return password;
}
#Column(name = "PERSON_ROLE", unique = false, nullable = false, length = 30)
public RoleEnum getRole() {
return role;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "idOwner")
public List<Task> getLstTasks() {
return lstTasks;
}
//Setters
}
Task.java
#Entity
#Table(name="tasks", uniqueConstraints =
#UniqueConstraint(columnNames = "TASK_ID"))
public class Task implements Serializable {
private int id;
private String name;
private String description;
private int idOwner;
public Task(int id, String name, int idOwner) {
this.id = id;
this.name = name;
this.idOwner = idOwner;
}
// <editor-fold defaultstate="collapsed" desc="Getters">
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "TASK_ID", unique = true, nullable = false)
public int getId() {
return id;
}
#Column(name = "TASK_NAME")
public String getName() {
return name;
}
#Column(name = "TASK_DESCRIPTION")
public String getDescription() {
return description;
}
#Column(name = "TASK_ID_OWNER")
public int getIdOwner() {
return idOwner;
}
// </editor-fold>
//Setters
}
Can somebody tell/show/explain me what I have to do exactly, to make this work?
Currently your mapping should linking ownerId instead of Task class.
Change your Task class to this
private Person person;
#ManyToOne
#JoinColumn(name = "TASK_ID_OWNER")
public Person getPerson() {
return person;
}
In your Person entity you have declared one-to-many relationship with Task entity like this:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "idOwner")
public List<Task> getLstTasks() {
return lstTasks;
}
Here you have given idOwner to mappedBy attribute, it means you are telling hibernate that there is property in Task class called idOwner which is of type Person.
So you have to modify your Tasks class like this (Changing the variable type from int to Person):
private Person idOwner;
#ManyToOne
#JoinColumn(name = "TASK_ID_OWNER")
public Person getIdOwner() {
return idOwner;
}
public void setIdOwner(Person idOwner) {
this.idOwner=idOwner;
}
If you remove the #JoinColumn annotation then hibernate will create a Join table for your relationship, else it will just create a foreign key in Task table with foreign key column name as TASK_ID_OWNER.