below is my 2 entities:
package dev.proj.project.application.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;
#Getter
#Setter
#NoArgsConstructor
#Entity
#Table(name = "user")
public class User {
#Id
#NotNull
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false, nullable = false)
public int id;
#NotNull
#Column(name="firstname")
private String firstname;
#NotNull
#Column(name="lastname")
private String lastname;
#NotNull
#Column(name="email")
private String email;
#NotNull
#Column(name="password")
private String password;
#JsonIgnore
#OneToMany(mappedBy="user", cascade = CascadeType.ALL)
private List<Address> address;
}
package dev.proj.project.application.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;
#Getter
#Setter
#NoArgsConstructor
#Entity
#Table(name = "address")
public class Address {
#Id
#NotNull
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false, nullable = false)
private int id;
#NotNull
#Column(name="street")
private String street;
#NotNull
#Column(name="house")
private String house;
#NotNull
#Column(name="flat")
private String flat;
#NotNull
#Column(name="code")
private String code;
#NotNull
#Column(name="city")
private String city;
#ManyToOne(optional = false)
#JoinColumn(name = "user_id",nullable = false,updatable = true,insertable = true)
private User user;
}
I want to create User->Address One-to-many relationship, but if I made post request to /address:
{
"street": "ulicanewnew",
"house": "5",
"flat": "2",
"code": "20-001",
"city": "warsaw",
"user_id": 1
}
user_id is null in my address table:
Why foreign key in address table is always null?
Do you see what is wrong here?
With direct sql inserts to db - everything works fine
I changed request to:
{
"street": "dyr",
"house": "5",
"flat": "2",
"code": "20-001",
"city": "warsaw",
"user": {
"id": 50
}
}
and it works, but question for now: how to use
"user_id" : 50
in my request, instead of
"user": {
"id": 50
}
?
Try adding below changes to your address entity.
#JoinColumn(name = "user_id")
#ManyToOne(targetEntity = User.class, fetch = FetchType.LAZY)
private User user;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
#Entity
#Table(name = "customer")
public class Customer {
...
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private int id;
#OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<DatabaseTable> databaseTables;
...
}
...
...
import org.hibernate.validator.constraints.Length;
import javax.persistence.*;
#Entity
#Table(name = "databasetable")
public class DatabaseTable {
...
#ManyToOne
#JoinColumn(name = "user_idFK")
private Customer customer;
....
}
Something like that works for me.
Related
I am using JPA + Spring Boot for my project. This is the first time I'm using JPA and I'm also very new to Spring Boot.
I want to create two tables file_perms and file_perm_values. I am able to get the definition of file_perms right. However, for my second table file_perm_values, I want to define a composite primary key that consists of the primary key of the file_perms, i.e., id and another String file_id. When I write the definition shown below and use the DDL creation button of Intellij, I get the error Caused by: java.lang.IllegalStateException: The column type is undefined. Table - file_perm_values; Column - file_perm_id
What am I doing wrong?
Could some of the experts out there please help me understand what's the problem and how to fix this?
I'll be very grateful
package com.some.project.persistence.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.ZonedDateTime;
import java.util.UUID;
#Entity
#Getter
#Builder
#NoArgsConstructor
#AllArgsConstructor
#ToString(onlyExplicitlyIncluded = true)
#Table(name = "file_perms")
public class FilePermsEntity {
#Id
#GeneratedValue
#Builder.Default
#ToString.Include
#Column(name = "id", nullable = false)
private UUID id = null;
#ToString.Include
#Column(name = "perm_name", nullable = false)
private String permName;
#ToString.Include
#Column(name = "is_active", nullable = false)
private boolean active;
#ToString.Include
#Column(name = "perm_guid")
private String permGuid;
#ToString.Include
#Column(name = "perm_index")
private int permIndex;
#CreatedDate
#Builder.Default
#ToString.Include
#Column(name = "created_at")
private ZonedDateTime createdAt = ZonedDateTime.now();
#Builder.Default
#ToString.Include
#LastModifiedDate
#Column(name = "updated_at")
private ZonedDateTime updatedAt = ZonedDateTime.now();
}
package com.some.project.persistence.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Builder
#ToString(onlyExplicitlyIncluded = true)
#Table(name = "file_perm_values")
public class FilePermValuesEntity {
#EmbeddedId
#ToString.Include
private FilePermValuesPrimaryKey id;
#ToString.Include
#Column(name = "value")
private String value;
#Getter
#Builder
#Embeddable
#NoArgsConstructor
#AllArgsConstructor
#ToString(onlyExplicitlyIncluded = true)
public static class FilePermValuesPrimaryKey implements Serializable {
private static final long serialVersionUID = 1223232L;
#MapsId
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "file_perm_id", nullable = false)
private FilePermsEntity filePermsEntity;
#ToString.Include
#Column(name = "file_id", nullable = false)
private String fileId;
#Override
public boolean equals(Object o) {
...
}
#Override
public int hashCode() {
...
}
}
}
The code below solved my problem:
#Entity
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Builder
#ToString(onlyExplicitlyIncluded = true)
#Table(name = "file_perm_values")
public class FilePermValuesEntity {
#EmbeddedId
#ToString.Include
private FilePermValuesPrimaryKey id;
#MapsId("filePermId")
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "file_perm_id")
private FilePermsEntity filePermsEntity;
#ToString.Include
#Column(name = "value")
private String value;
#Getter
#Builder
#Embeddable
#NoArgsConstructor
#AllArgsConstructor
#ToString(onlyExplicitlyIncluded = true)
public static class FilePermValuesPrimaryKey implements Serializable {
private static final long serialVersionUID = 1223232L;
#ToString.Include
#Column(name = "file_perm_id", nullable = false)
private UUID filePermId;
#ToString.Include
#Column(name = "file_id", nullable = false)
private String fileId;
#Override
public boolean equals(Object o) {
...
}
#Override
public int hashCode() {
...
}
}
}
I am in the process of adding a DTO layer to a restful api. Before, the program used entity (Recipe and Ingredient) directly and now I added a new DTO layer in between (RecipeDTO IngredientDTO). However, the moment I made the change I started getting Null values from #RequestBody. Each recipe contains a list of Ingredients and it is the list of ingredients that are returning null values, the recipe by itself is returning fine.
The controller looks like this
package com.example.recipes.controller;
import com.example.recipes.DTO.RecipeDTO;
import com.example.recipes.Service.RecipeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/*...*/
#PostMapping(path = "/post")
public void postRecipes(#RequestBody RecipeDTO recipeDTO){
recipeService.postRecipes(recipeDTO);
}
/*...*/
Recipe Entity
package com.example.recipes.Entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.List;
#Data
#Entity
#Table(name = "recipe", schema = "public")
#AllArgsConstructor
#NoArgsConstructor
public class Recipe {
#Id
#GeneratedValue(
strategy = GenerationType.IDENTITY
)
#Column(name = "id", updatable = false, nullable = false)
private long id;
#Column(name = "name")
private String name;
#Column(name = "instructions")
private String instructions;
#OneToMany(mappedBy = "recipe")
private List<Ingredient> ingredients;
#JsonProperty("date_added")
private String dateAdded = String.valueOf(LocalDateTime.now());
#JsonProperty("last_edited")
private String lastEdited = String.valueOf(LocalDateTime.now());
}
RecipeDTO
package com.example.recipes.DTO;
import lombok.*;
import javax.persistence.OneToMany;
import java.time.LocalDateTime;
import java.util.List;
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#ToString
public class RecipeDTO {
private long id;
private String name;
private String instructions;
private List<IngredientDTO> ingredientsDTO;
private String dateAdded = String.valueOf(LocalDateTime.now());
private String lastEdited = String.valueOf(LocalDateTime.now());
public RecipeDTO(long id, String name, String instructions, String dateAdded, String lastEdited) {
this.id = id;
this.name = name;
this.instructions = instructions;
this.dateAdded = dateAdded;
this.lastEdited = lastEdited;
}
}
Ingredient Entity
package com.example.recipes.Entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.persistence.*;
#Data
#Entity
#Table(name = "Ingredient")
#NoArgsConstructor
public class Ingredient {
#Id
#GeneratedValue(
strategy = GenerationType.IDENTITY
)
#JsonProperty("ingredient_id")
private long ingredient_ID;
#JsonProperty("ingredient_name")
private String ingredientName;
#Column(name = "amount")
private int amount;
#Column(name = "unit")
private String unit;
#ManyToOne
#JoinColumn(name = "recipe_id")
#ToString.Exclude
#JsonIgnore
private Recipe recipe;
}
IngredientDTO
package com.example.recipes.DTO;
import lombok.*;
#Data
#AllArgsConstructor
#NoArgsConstructor
public class IngredientDTO {
private long ingredientID;
private String ingredientName;
private int amount;
private String unit;
}
the json i sent
{
"name":"unique2",
"ingredients":[
{
"ingredient_name":"Atlantic",
"amount":13,
"unit":"ton"
},
{
"ingredient_name":"Pacific",
"amount":15,
"unit":"boatload"
},
{
"ingredient_name":"Indian",
"amount":38,
"unit":"trucload"
}
],
"instructions":"easy on the salt"
}
and the #requestbody the ingredientsDTO is null
this is recipe: RecipeDTO(id=0, name=unique2, instructions=easy on the salt, ingredientsDTO=null, dateAdded=2022-08-08T15:04:10.678748100, lastEdited=2022-08-08T15:04:10.678748100)
Edit: I have just tried copying the code from the entity classes and pasting them in the DTO classes and it still returning null...
package com.example.recipes.DTO;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.List;
#Data
#Entity
#Table(name = "recipe", schema = "public")
#AllArgsConstructor
#NoArgsConstructor
public class RecipeDTO {
#Id
#GeneratedValue(
strategy = GenerationType.IDENTITY
)
#Column(name = "id", updatable = false, nullable = false)
private long id;
#Column(name = "name")
private String name;
#Column(name = "instructions")
private String instructions;
#OneToMany(mappedBy = "recipeDTO")
private List<IngredientDTO> ingredientDTOs;
#JsonProperty("date_added")
private String dateAdded = String.valueOf(LocalDateTime.now());
#JsonProperty("last_edited")
private String lastEdited = String.valueOf(LocalDateTime.now());
public RecipeDTO(long id, String name, String instructions, String dateAdded, String lastEdited) {
this.id = id;
this.name = name;
this.instructions = instructions;
this.dateAdded = dateAdded;
this.lastEdited = lastEdited;
}
}
package com.example.recipes.DTO;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.persistence.*;
#Data
#Entity
#Table(name = "Ingredient")
#NoArgsConstructor
public class IngredientDTO {
#Id
#GeneratedValue(
strategy = GenerationType.IDENTITY
)
#JsonProperty("ingredient_id")
private long ingredientID;
#JsonProperty("ingredient_name")
private String ingredientName;
#Column(name = "amount")
private int amount;
#Column(name = "unit")
private String unit;
#ManyToOne
#JoinColumn(name = "recipe_id")
#ToString.Exclude
#JsonIgnore
private RecipeDTO recipeDTO;
public IngredientDTO(long ingredientID, String ingredientName, int amount, String unit) {
this.ingredientID = ingredientID;
this.ingredientName = ingredientName;
this.amount = amount;
this.unit = unit;
}
}
#RequestBody
this is recipe: RecipeDTO(id=0, name=unique2, instructions=easy on the salt, ingredientDTOs=null, dateAdded=2022-08-08T15:24:19.325806500, lastEdited=2022-08-08T15:24:19.325806500)
these are the ingredients: null
this is ingredientDTO: null
this is ingredientDTO: null
Edit2: I tried posting only the ingredientDTO and the #RequestBody was able to pick it up just fine
//this is fine
public void testRecipePost(#RequestBody IngredientDTO ingredientDTO) {
System.out.println("ingredientDTO: " + ingredientDTO);
}
You can replace
#OneToMany(mappedBy = "recipeDTO")
private List<IngredientDTO> ingredientDTOs;
to
#OneToMany(mappedBy = "recipeDTO")
private List<IngredientDTO> ingredients;
Or adding
#JsonProperty("ingredients")
Example:
#JsonProperty("ingredients")
#OneToMany(mappedBy = "recipeDTO")
private List<IngredientDTO> ingredientDTOs;
The reason for null is because Jackson doesn't know how to deserialise your fields properly with different names.
In the json, the name is ingredients but, in the DTO, it is ingredientsDTO. Those 2 need to match.
You request
{
"name":"unique2",
"ingredients":[...]
here the name of array you are passing in Json is different in the entity you are using.
Your DTO
#OneToMany(mappedBy = "recipeDTO")
private List<IngredientDTO> ingredientDTOs;
The name of fields in JSON request and Entity must match.
Change the name of field private List<IngredientDTO> ingredientDTOs; to ingredients.
I got two classes:
package com.educationalcenter.demo.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.*;
import lombok.experimental.FieldDefaults;
import javax.persistence.*;
import java.util.List;
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Setter
#Getter
#FieldDefaults(level = AccessLevel.PRIVATE)
#Entity
#Table(name = "bankworker")
public class Bankworker {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long bankworkerId;
#Column(nullable = false)
String Fname;
#Column(nullable = false)
String Lname;
#Column(nullable = false, unique = true)
String Login;
#Column(nullable = false)
String Password;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "branch_id", referencedColumnName = "branchId")
#JsonManagedReference
Branch branch;
#OneToOne(mappedBy = "managerId")
#JsonBackReference
Branch branchOneToOne;
#OneToMany(mappedBy = "creditorId")
#JsonBackReference
List<CreditRequest> creditRequests;
}
Bankworker enitity must show: bankworker_id, Fname, Lname, Login, Password, branch_id
package com.educationalcenter.demo.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.*;
import lombok.experimental.FieldDefaults;
import javax.persistence.*;
import java.util.List;
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Setter
#Getter
#FieldDefaults(level = AccessLevel.PRIVATE)
#Entity
#Table(name = "branch")
public class Branch {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long branchId;
#Column(nullable = false, unique = true)
String address;
#Column(nullable = false)
String city;
String country;
#OneToOne
#JoinColumn(name = "manager_id", referencedColumnName = "bankworkerId", unique = true)
#JsonManagedReference
Bankworker managerId;
#OneToMany(mappedBy = "branch")
#JsonBackReference
List<Bankworker> bankworkers;
}
Branch entity must show: branch_id, address, city, country, manager_id.
So, when I try to get with jpa findAll() methods all branches or bankworkers, it gives this:
[
{
"bankworkerId": 1,
"branch": {
"branchId": 1,
"address": "Lev Tolstoy 3, 17",
"city": "Bishkek",
"country": "Kyrgyzstan",
"managerId": {
"bankworkerId": 1,
"branch": {
"branchId": 1,
"address": "Lev Tolstoy 3, 17",
"city": "Bishkek",
"country": "Kyrgyzstan",
"managerId": {
"bankworkerId": 1,
"branch": {
"branchId": 1,
"address": "Lev Tolstoy 3, 17",
"city": "Bishkek",
"country": "Kyrgyzstan",
"managerId": {
"bankworkerId": 1,
etc.
In short, it calls data about itself, so it never stops.
I'd like to know how I can handle this without sacrificing any fields
I tried to test the API, but I get a 404 status. Any advice?
After testing:
{
"timestamp": "2022-03-29T01:50:58.126+00:00",
"status": 404,
"error": "Not Found",
"path": "/api/v1/users"
}
I'm not sure if the problem is in the database itself or something went wrong with my code for the controller?
User Table:
package com.infosys.models;
import com.infosys.role_type.RoleType;
import lombok.Data;
import javax.persistence.*;
#Entity
#Table(name = "users")
#Data
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "username")
private String userName;
#Column(name = "password")
private String password;
#Column(name = "email" )
private String email;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#ManyToOne
#JoinColumn(name = "role_id", nullable = false)
private RoleType role;
}
Role Table
package com.infosys.models;
import com.infosys.role_type.RoleType;
import lombok.Data;
import javax.persistence.*;
#Entity
#Table(name="role")
#Data
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "role_id")
private RoleType role_type;
}
Employee Table:
package com.infosys.models;
import com.infosys.role_type.RoleType;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalTime;
import java.util.*;
#Entity
#Table(name="employee")
#Data
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#ManyToOne
#JoinColumn(name = "role_id", nullable = false)
private RoleType role;
#ManyToOne
#JoinTable(name = "employee_has_manager",
joinColumns = #JoinColumn(name = "employee_id"),
inverseJoinColumns = #JoinColumn(name = "manager_id")
)
private Set<Manager> manager = new HashSet<>();
#ManyToOne
#JoinColumn(name = "user_id", nullable = false)
private User users;
#Column(name = "start_time")
private LocalTime startTime;
#Column(name = "end_time")
private LocalTime endTime;
#Column(name = "total_hrs")
private Long totalHrs;
}
Manager Table:
package com.infosys.models;
import com.infosys.role_type.RoleType;
import lombok.Data;
import javax.persistence.*;
import javax.persistence.Table;
import java.util.*;
#Entity
#Table(name="manager")
#Data
public class Manager {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#ManyToOne
#JoinColumn(name = "user_id", nullable = false)
private User users;
#ManyToOne
#JoinColumn(name = "role_id", nullable = false)
private RoleType role;
#OneToMany(mappedBy = "manager")
private Set<Employee> employee = new HashSet<>();
#Column(name = "employee_review")
private String employeeReview;
}
User Repository:
package com.infosys.repositories;
import com.infosys.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
User Controller:
package com.infosys.controllers;
import com.infosys.models.User;
import com.infosys.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
#RestController
#RequestMapping("/api/v1/")
public class UserController {
#Autowired
private UserRepository userRepository;
// get all users
#GetMapping("/users")
public String getAllUsers() {
return "Test";
}
}
Spring App:
package com.infosys;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
#ComponentScan("com.infosys.repositories")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I am creating one feeds table which has one to many mapping with comments and many to one mapping with users table. But when i am annotating the user_table field in my feeds entity as #ManyToOne i am getting error like #OneToOne or #ManyToOne on xxx references an unknown entity: java .util.Set but when i am annotating it with #ManyToMany it is not throwing any error and the table are getting created. Can anyone explain me why
package com.incture.metrodata.entity;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
#Entity
#Getter
#Setter
#ToString
#Table(name = "FEEDS_DETAILS")
public class FeedsDo implements BaseDo {
/**
*
*/
private static final long serialVersionUID = -2035537433672391211L;
#Id
#Column(name = "FEED_ID")
private String feedId;
#Column(name = "BODY")
private String body;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_AT")
private Date createdAt;
#Column(name = "CREATED_BY")
private String createdBy;
#Column(name = "TITLE")
private String title;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "UPDATED_AT")
private Date updatedAt;
#Column(name = "UPDATED_BY")
private String updatedBy;
#Column(name = "IS_DELETED")
private int isDeleted = 0;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "FEEDS_USERS", joinColumns = { #JoinColumn(name = "FEED_ID")}, inverseJoinColumns = { #JoinColumn(name = "USER_ID") })
private Set<UserDetailsDo> user = new HashSet<UserDetailsDo>(0);
#OneToMany(targetEntity = CommentsDo.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<CommentsDo> comments;
#Override
public Object getPrimaryKey()
{
return feedId;
}
}
package com.incture.metrodata.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "COMMENTS")
public class CommentsDo implements BaseDo {
/**
*
*/
private static final long serialVersionUID = 5180603287069572120L;
#Id
#Column(name = "COMMENT_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long commentId;
#Lob
private String comment;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_AT")
private Date createdAt;
#Column(name = "CREATED_BY")
private String createdBy;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "UPDATED_AT")
private Date updatedAt;
#Column(name = "IS_DELETED")
private int isDeleted=0;
#Override
public Object getPrimaryKey() {
return commentId;
}
}
package com.incture.metrodata.entity;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Where;
import lombok.Data;
import lombok.ToString;
#Entity
#Data
#ToString
#Table(name = "USER_DETAILS")
#DynamicUpdate(true)
#Where(clause = "DELETE = 0")
public class UserDetailsDo implements BaseDo {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "USER_ID",length=50)
private String userId;
#Column(name = "FIRST_NAME",length=100)
private String firstName;
#Column(name = "LAST_NAME",length=100)
private String lastName;
//#Formula(value = " concat(FIRST_NAME, ' ', LAST_NAME) ")
#Column(name = "NAME",length=100)
private String name;
#ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private RoleDetailsDo role;
#Column(name = "TELEPHONE",length=50)
private String telephone;
#Column(name = "CREATED_BY",length=50)
private String createdBy;
#Column(name = "UPDATED_BY",length=50)
private String updatedBy;
#Column(name = "MOBILE_TOKEN")
#Lob
private String mobileToken;
#Column(name = "WEB_TOKEN")
#Lob
private String webToken;
#Column(name = "LONGITUDE")
private Double longitude;
#Column(name = "LATITUDE")
private Double latitude;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_DATE")
private Date createdDate;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_AT")
private Date createdAt;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "UPDATED_AT")
private Date updateAt;
#Column(name = "EMAIL",length=100)
private String email;
#Column(name = "PARENT_ID",length=100)
private String parentId;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_LOGIN_TIME")
private Date lastLogedIn;
#Column(name = "TRACK_FREQUENCY")
#ColumnDefault("'30'")
private Long trackFreq;
#ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinTable(name = "USERS_WAREHOUSE_MAPPING", joinColumns = { #JoinColumn(name = "USER_ID") }, inverseJoinColumns = {
#JoinColumn(name = "WARE_HOUSE_ID") })
private Set<WareHouseDetailsDo> wareHouseDetails = new HashSet<WareHouseDetailsDo>(0);
#ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinTable(name = "USERS_COURIER_MAPPING", joinColumns = { #JoinColumn(name = "USER_ID") }, inverseJoinColumns = {
#JoinColumn(name = "COURIER_ID") })
private Set<CourierDetailsDo> courierDetails = new HashSet<CourierDetailsDo>(0);
#Column(name = "DELETE")
#ColumnDefault("'0'")
private Integer deleted = 0;
public void setDeleted() {
this.deleted = 1;
}
#Override
public Object getPrimaryKey() {
return userId;
}
}
You have a one-directional relationship:
#OneToMany(targetEntity = CommentsDo.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<CommentsDo> comments;
And hibernate doesn't know, which column to use to join those entities. The best would be to add relationship definition on child side. You need to specify #JoinColumn, something like:
#JoinColumn(name = "feeds_do_id")
private FeedsDo feedsDo;
in CommentsDo class. Instead of feeds_do_id there should be a foreign key.