Vaadinversion: 14.4.1
spring-boot-starter-parent: 2.2.10RELEASE
I have two items in my grid. These two items looks like:
Kontakt{id=11657f9e-c4f4-414f-aab2-618252db9b06'vorname='test1'...
Kontakt{id=8da74f38-2072-4fb0-8c74-aede661f02b5'vorname='test'...
But the grid only displays only one items and so oft like the "itemslist.size()"
Also they react as "one row". So I can like on the first and both get selected.
These are my #Entity(s)
#Entity
#Table(name = "std_kunde")
#Data
public class Kunde extends Kontakt {
public Kunde() {
super();
}
#Override
public String toString() {
return super.toString();
}
}
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
#Data
public abstract class Kontakt extends BasicEntity {
private String vorname;
private String name;
...
public Kontakt() {
super();
}
#Override
public String toString() {
return "Kontakt{" +
"id=" + getId() + '\'' +
"vorname='" + vorname + '\'' +
...
'}';
}
}
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
#Data
public abstract class BasicEntity {
#Id
#GenericGenerator(name = "id_generator", strategy = "....KeyGenerator")
#GeneratedValue(generator = "id_generator")
#Column(length = 128)
private String id;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "create_date")
private Date createDate;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "modify_date")
private Date modifyDate;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "basicEntity")
private List<Anhang> anhangList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "basicEntity")
private List<Notiz> notizList;
public BasicEntity() {
anhangList = new ArrayList<>();
notizList = new ArrayList<>();
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public boolean equals(Object o){
if(null == o)
return false;
if(!(o instanceof BasicEntity))
return false;
BasicEntity b = (BasicEntity) o;
return b.getId().equals(this.getId());
}
}
And also the Grid code
#Autowired
private KundeService kundeService;
private Grid<Kunde> g;
public Dashboard() {
g = new Grid<>(Kunde.class);
g.addColumn(Kunde::getVorname).setHeader("Vorname");
g.setSizeFull();
setSizeFull();
add(g);
}
I tested to build a Grid based upon an other entiy and it worked like it should. Its like the first time I have this behaivor but I dont know how actually to debug it...
EDIT 29.10.2020 ---------------------------------------------------------------
This is the #Entity (Notiz) which works like expected.
UI-Code
private Grid<Kunde> g;
private Grid<Notiz> n;
public Dashboard() {
g = new Grid<>(Kunde.class);
g.addColumn(Kunde::getId).setHeader("ID");
g.addColumn(Kunde::getVorname).setHeader("Vorname");
g.setSizeFull();
n = new Grid<>(Notiz.class);
n.addColumn(Notiz::getId).setHeader("ID");
n.addColumn(Notiz::getTitel).setHeader("Titel");
n.setSizeFull();
setSizeFull();
add(g,n);
}
#PostConstruct
private void loadValues(){
g.setItems(kundeService.findAll());
n.setItems(notizService.findAll());
}
#Entity
#Table(name = "ld_notiz")
#Data
public class Notiz extends BasicEntitySystemFeatures {
private String titel;
#Column(length = 5000) //TODO
private String content;
private boolean abgeschlossen = false;
#Enumerated(EnumType.STRING)
private NOTIZ_TYP notizTyp;
public enum NOTIZ_TYP {
NOTIZ,
ERINNERUNG
}
#ManyToOne
private BasicEntity basicEntity;
public Notiz() {
super();
}
}
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
#Data
public abstract class BasicEntitySystemFeatures {
#Id
#GenericGenerator(name = "id_generator", strategy = "...KeyGenerator")
#GeneratedValue(generator = "id_generator")
#Column(length = 128)
private String id;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "create_date")
private Date createDate;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "modify_date")
private Date modifyDate;
public BasicEntitySystemFeatures() {
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public boolean equals(Object o){
if(null == o)
return false;
if(!(o instanceof BasicEntitySystemFeatures))
return false;
BasicEntitySystemFeatures b = (BasicEntitySystemFeatures) o;
return b.getId().equals(this.getId());
}
Related
I put jsonignore all over my entity account, and a custom serializer on the Friend field.
now that I want to recover an account via controller no more worries, however as soon as I try to recover it in service with the id or other I have the following error:
java.lang.StackOverflowError: null
Entity:
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
public class Account {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int account_id;
private String firstname;
private String lastname;
#Column(unique = true)
private String username;
private boolean active;
private String avatar;
#JsonIgnore
#ManyToMany
#JoinTable(name = "ludo",
joinColumns = #JoinColumn(name = "id_account"),
inverseJoinColumns = #JoinColumn(name = "id_boardGame"))
private List<Boardgame> boardgameList;
#JsonIgnore
#OneToMany(mappedBy = "account")
List<Friends> FriendsList;
#ManyToOne
#JoinColumn(name="FK_country_Id",nullable = true,referencedColumnName = "country_id")
private Country country;
#ManyToOne
#JoinColumn(name="FK_language_Id",nullable = true,referencedColumnName = "language_id")
private Language language;
#Column(updatable = false)
#CreationTimestamp
private LocalDateTime createdAt;
}
Serializer:
public class FriendsSerializer extends StdSerializer<Friends> {
public FriendsSerializer() {
this(null);
}
public FriendsSerializer(Class<Friends> t) {
super(t);
}
#Override
public void serialize(Friends friends, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("account_id", friends.getFriend().getAccount_id());
jsonGenerator.writeStringField("username", friends.getFriend().getUsername());
jsonGenerator.writeStringField("createdAt", String.valueOf(friends.getCreatedAt()));
jsonGenerator.writeBooleanField("active", friends.isActive());
jsonGenerator.writeStringField("avatar",friends.getFriend().getAvatar());
jsonGenerator.writeFieldName("country");
jsonGenerator.writeObject(friends.getFriend().getCountry());
jsonGenerator.writeEndObject();
}
}
AccountService:
#Override
public ApiResponse getFriendNoConfirmation(Account account) {
if(account != null && account.getAccount_id() != 0){
// List<Friends> listIdAccount = this.friendRepository.getFriendsNoConfirmation(account.getAccount_id());
List<Integer> listIdAccount = this.friendRepository.getFriendsNoConfirmation(account.getAccount_id());
if(listIdAccount != null){
List<Account> listAccount = new ArrayList<>();
for(int idAccount: listIdAccount){
System.out.println(idAccount);
Account friendAccount = this.getAcountById(idAccount);
System.out.println(friendAccount);
listAccount.add(friendAccount);
}
return new ApiResponse(true, listIdAccount,BASE_CODE + "friendListNoConfirm.success");
}else{
return new ApiResponse(true, null,BASE_CODE + "friendListNoConfirm.error");
}
}else{
return new ApiResponse(true, null,BASE_CODE + "friendListNoConfirm.error");
}
}
#Override
public Account getAcountById(Integer id){
return this.accountRepository.getAccountById(id);
}
I removed the mapped by and to get my objects I make queries by joining the tables
I have several entities but there are three entities that have relationship on each other(Car,CarCategory,Order)
Car entity :
#Entity
#Table(name = "car_info")
#Getter
#Setter
public class Car implements Serializable {
private static final long serialVersionUID = -1473879605284728654L;
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "carId", nullable = false)
private Long carId;
#Column(name = "numOfPas")
private int numOfPas;
#Column(name = "carState")
private String carState;
#Column(name = "carName", length = 25)
private String carName;
#Column(name = "carImage")
#Lob
private byte[] carImage;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "carCategory")
private CarCategory carCategory;
#OneToMany(mappedBy = "car", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Order> orders = new ArrayList<>();
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return Objects.equals(getCarId(), car.getCarId());
}
#Override
public int hashCode() {
return Objects.hash(getCarId());
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Car{");
sb.append("carId=").append(carId);
sb.append(", numOfPas=").append(numOfPas);
sb.append(", carState='").append(carState).append('\'');
sb.append(", carName='").append(carName).append('\'');
sb.append('}');
return sb.toString();
}
}
CarCategory entity :
#Entity
#Table(name = "car_category")
#Getter
#Setter
public class CarCategory implements Serializable {
private static final long serialVersionUID = -4179236910442782235L;
#Column(name = "carCategoryName", nullable = false, length = 15)
#Id
private String carCategoryName;
#Column(name = "costPerOneKilometer")
private double costPerOneKilometer;
#Column(name = "discountPerPrice")
private double discountPerPrice;
#Column(name = "carCategoryImage")
#Lob
private byte[] carCategoryImage;
#OneToMany(mappedBy = "carCategory", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Car> cars = new ArrayList<>();
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CarCategory that = (CarCategory) o;
return Objects.equals(getCarCategoryName(), that.getCarCategoryName());
}
#Override
public int hashCode() {
return Objects.hash(getCarCategoryName());
}
}
Order entity :
#Entity
#Table(name = "user_order", indexes = {
#Index(name = "idx_order_userid_carid_unq", columnList = "userId, carId", unique = true)
})
#Getter
#Setter
public class Order implements Serializable {
private static final long serialVersionUID = -4577879200654802752L;
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "orderId", nullable = false)
private Long orderId;
#Column(name = "userAddress", length = 60)
private String userAddress;
#Column(name = "userDestination", length = 60)
private String userDestination;
#Column(name = "orderCost")
private double orderCost;
#Column(name = "orderDate", columnDefinition = "DATETIME")
private LocalDateTime orderDate;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "userId")
private User user;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "carId")
private Car car;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Order order = (Order) o;
return Objects.equals(getOrderId(), order.getOrderId());
}
#Override
public int hashCode() {
return Objects.hash(getOrderId());
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Order{");
sb.append("orderId=").append(orderId);
sb.append(", userAddress='").append(userAddress).append('\'');
sb.append(", userDestination='").append(userDestination).append('\'');
sb.append(", orderCost=").append(orderCost);
sb.append(", orderDate=").append(orderDate);
sb.append('}');
return sb.toString();
}
}
As you can see Order has relationship to car and carCategory has relationship to car
So for converting to dto I have this assembler which will be used in service layer
Assembler interface :
public interface Assembler<E,D >{
D mergeAggregateIntoDto(E entity);
E mergeDtoIntoAggregate(D dto);
}
CarCategoryAssembler :
#Service
public class CarCategoryAssembler implements Assembler<CarCategory, CarCategoryDto> {
#Override
public CarCategoryDto mergeAggregateIntoDto(CarCategory entity) {
CarCategoryDto carCategoryDto = new CarCategoryDto();
carCategoryDto.setCarCategoryName(entity.getCarCategoryName());
carCategoryDto.setCostPerOneKilometer(entity.getCostPerOneKilometer());
carCategoryDto.setCarCategoryImage(entity.getCarCategoryImage());
carCategoryDto.setDiscountPerPrice(entity.getDiscountPerPrice());
carCategoryDto.setCars(entity.getCars().stream().map(this::mergeAggregateIntoDto).collect(Collectors.toList()));
return carCategoryDto;
}
#Override
public CarCategory mergeDtoIntoAggregate(CarCategoryDto dto) {
CarCategory carCategory = new CarCategory();
carCategory.setCarCategoryImage(dto.getCarCategoryImage());
carCategory.setCarCategoryName(dto.getCarCategoryName());
carCategory.setDiscountPerPrice(dto.getDiscountPerPrice());
carCategory.setCostPerOneKilometer(dto.getCostPerOneKilometer());
carCategory.setCars(dto.getCars().stream().map(carDto -> {
Car car =mergeDtoIntoAggregate(carDto);
car.setCarCategory(carCategory);
return car;
}).collect(Collectors.toList()));
return carCategory;
}
private CarDto mergeAggregateIntoDto(Car car){
CarDto carDto = new CarDto();
carDto.setCarCategory(car.getCarCategory().getCarCategoryName());
carDto.setCarId(car.getCarId());
carDto.setCarImage(car.getCarImage());
carDto.setCarState(car.getCarState());
carDto.setNumOfPas(car.getNumOfPas());
carDto.setCarName(car.getCarName());
return carDto;
}
private Car mergeDtoIntoAggregate(CarDto dto) {
Car car = new Car();
car.setCarId(dto.getCarId());
car.setCarImage(dto.getCarImage());
car.setCarName(dto.getCarName());
car.setCarState(dto.getCarState());
car.setNumOfPas(dto.getNumOfPas());
return car;
}
}
So if I need OrderAssembler I will have duplicate code when I'm converting Car to Car Dto and back. So how can I prevent duplicate code? Thanks.
this is my first post, so please bear with me if i do make any errors.
I get an error " java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST"
whenever i want to query(add,edit,delete) the database.
The tables related are sponsors and donations. There is a one to many relationship between them. Classes below:
Sponsors
#Entity
#Table(name = "SPONSORS")
#NamedQueries({
#NamedQuery(name = "Sponsors.findAll", query = "SELECT s FROM Sponsors s")})
public class Sponsors implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "SPONSORID")
private Short sponsorid;
#Basic(optional = false)
#Column(name = "NAME")
private String name;
#Basic(optional = false)
#Column(name = "SURNAME")
private String surname;
#Basic(optional = false)
#Column(name = "ADDRESS")
private String address;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "sponsorid")
private List<Donations> donationsList;
public Sponsors() {
}
public Sponsors(Short sponsorid) {
this.sponsorid = sponsorid;
}
public Sponsors(Short sponsorid, String name, String surname, String address) {
this.sponsorid = sponsorid;
this.name = name;
this.surname = surname;
this.address = address;
}
public Short getSponsorid() {
return sponsorid;
}
public void setSponsorid(Short sponsorid) {
this.sponsorid = sponsorid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Donations> getDonationsList() {
return donationsList;
}
public void setDonationsList(List<Donations> donationsList) {
this.donationsList = donationsList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (sponsorid != null ? sponsorid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Sponsors)) {
return false;
}
Sponsors other = (Sponsors) object;
if ((this.sponsorid == null && other.sponsorid != null) || (this.sponsorid != null && !this.sponsorid.equals(other.sponsorid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Pat.Sponsors[ sponsorid=" + sponsorid + " ]";
}
}
Donations:
#Entity
#Table(name = "DONATIONS")
#NamedQueries({
#NamedQuery(name = "Donations.findAll", query = "SELECT d FROM Donations d")})
public class Donations implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "DONATIONID")
private Short donationid;
#Basic(optional = false)
#Column(name = "DONATIONDATE")
#Temporal(TemporalType.DATE)
private Date donationdate;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "DONATIONAMOUNT")
private Double donationamount;
#JoinColumn(name = "SPONSORID", referencedColumnName = "SPONSORID")
#ManyToOne(optional = false)
private Sponsors sponsorid;
public Donations() {
}
public Donations(Short donationid) {
this.donationid = donationid;
}
public Donations(Short donationid, Date donationdate) {
this.donationid = donationid;
this.donationdate = donationdate;
}
public Short getDonationid() {
return donationid;
}
public void setDonationid(Short donationid) {
this.donationid = donationid;
}
public Date getDonationdate() {
return donationdate;
}
public void setDonationdate(Date donationdate) {
this.donationdate = donationdate;
}
public Double getDonationamount() {
return donationamount;
}
public void setDonationamount(Double donationamount) {
this.donationamount = donationamount;
}
public Sponsors getSponsorid() {
return sponsorid;
}
public void setSponsorid(Sponsors sponsorid) {
this.sponsorid = sponsorid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (donationid != null ? donationid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Donations)) {
return false;
}
Donations other = (Donations) object;
if ((this.donationid == null && other.donationid != null) || (this.donationid != null && !this.donationid.equals(other.donationid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Pat.Donations[ donationid=" + donationid + " ]";
}
}
The field
#ManyToOne(optional = false)
private Sponsors sponsorid;
in the Donations entity is not configured for cascading. Try changing it to:
#ManuToOne(optional = false, cascade = CascadeType.ALL)
private Sponsors sponsorid;
Please help me in accessing Employee object in the below code using JAXB annotations. The application was developed in JPA SPRING. We are unable to access sub-object properties i.e, Employee properties
RESOURCE CORE FILE
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlRootElement(name="resource")
#Entity
#Table(name = "resource")
public class Resource implements java.io.Serializable {
private Integer resourceId;
private String resourceCode;
private String resourceName;
private String resourceNumber;
private Employee employee;
public Resource() {
}
public Resource(Employee employee,String resourceCode, String resourceName,
String resourceNumber
) {
this.employee = employee;
this.resourceCode = resourceCode;
this.resourceName = resourceName;
this.resourceNumber = resourceNumber;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "resource_id", unique = true, nullable = false)
public Integer getResourceId() {
return this.resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
#Column(name = "resource_code")
public String getResourceCode() {
return this.resourceCode;
}
public void setResourceCode(String resourceCode) {
this.resourceCode = resourceCode;
}
#Column(name = "resource_number")
public String getResourceNumber() {
return this.resourceNumber;
}
public void setResourceNumber(String resourceNumber) {
this.resourceNumber = resourceNumber;
}
#Column(name = "resource_name")
public String getResourceName() {
return this.resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "employee_id")
public Employee getEmployee() {
return this.employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
EMPLOYEE CORE FILE
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlRootElement(name="employee")
#Entity
#Table(name = "employee")
public class Employee implements java.io.Serializable {
private Integer employeeId;
private String employeeCode;
private String employeeName;
private List<Resource> resources = new ArrayList<Resource>(0);
public Employee() {
}
public Employee(String employeeCode, String employeeName,List<Resource> resources
) {
this.employeeCode = employeeCode;
this.employeeName = employeeName;
this.resources = resources;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "employee_id", unique = true, nullable = false)
public Integer getEmployeeId() {
return this.employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
#Column(name = "employee_code")
public String getEmployeeCode() {
return this.employeeCode;
}
public void setEmployeeCode(String employeeCode) {
this.employeeCode = employeeCode;
}
#Column(name = "employee_name")
public String getEmployeeName() {
return this.employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "employee")
public List<Resource> getResources() {
return this.resources;
}
public void setResources(List<Resource> resources) {
this.resources = resources;
}
}
You have to use the FetchType : Eager in RESOURCE CORE FILE of getEmployee() Method. Lazy fetch type is pulling only the parent object. Eager is pulling both.
I have a table Post and Post_Image
#Entity
#Table(name = "post")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Post.findAll", query = "SELECT p FROM Post p"),
#NamedQuery(name = "Post.findByPostId", query = "SELECT p FROM Post p WHERE p.postId = :postId"),
#NamedQuery(name = "Post.findByTitle", query = "SELECT p FROM Post p WHERE p.title = :title"),
#NamedQuery(name = "Post.findByCreatedDatetime", query = "SELECT p FROM Post p WHERE p.createdDatetime = :createdDatetime")})
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "post_id")
private Integer postId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "title")
private String title;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "content")
private String content;
#Column(name = "created_datetime")
#Temporal(TemporalType.TIMESTAMP)
private Date createdDatetime;
#JoinColumn(name = "user_id", referencedColumnName = "user_id")
#ManyToOne(optional = false)
private User userId;
#JoinColumn(name = "post_type_id", referencedColumnName = "post_type_id")
#ManyToOne(optional = false)
private PostType postTypeId;
public Post() {
Date date = new Date();
this.createdDatetime =new Date(date.getTime());
}
public Post(Integer postId) {
this.postId = postId;
}
public Post(Integer postId, String title, String content) {
this.postId = postId;
this.title = title;
this.content = content;
}
public Integer getPostId() {
return postId;
}
public void setPostId(Integer postId) {
this.postId = postId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatedDatetime() {
return createdDatetime;
}
public void setCreatedDatetime(Date createdDatetime) {
this.createdDatetime = createdDatetime;
}
public User getUserId() {
return userId;
}
public void setUserId(User userId) {
this.userId = userId;
}
public PostType getPostTypeId() {
return postTypeId;
}
public void setPostTypeId(PostType postTypeId) {
this.postTypeId = postTypeId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (postId != null ? postId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Post)) {
return false;
}
Post other = (Post) object;
if ((this.postId == null && other.postId != null) || (this.postId != null && !this.postId.equals(other.postId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Post[ postId=" + postId + " ]";
}
}
and
#Entity
#Table(name = "post_image")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "PostImage.findAll", query = "SELECT p FROM PostImage p"),
#NamedQuery(name = "PostImage.findByPostImageId", query = "SELECT p FROM PostImage p WHERE p.postImageId = :postImageId"),
#NamedQuery(name = "PostImage.findByPath", query = "SELECT p FROM PostImage p WHERE p.path = :path"),
#NamedQuery(name = "PostImage.findByTitle", query = "SELECT p FROM PostImage p WHERE p.title = :title")})
public class PostImage implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "post_image_id")
private Integer postImageId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "path")
private String path;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "title")
private String title;
#JoinColumn(name = "post_id", referencedColumnName = "post_id")
#ManyToOne(optional = false)
private Post postId;
public PostImage() {
}
public PostImage(Integer postImageId) {
this.postImageId = postImageId;
}
public PostImage(Integer postImageId, String path, String title) {
this.postImageId = postImageId;
this.path = path;
this.title = title;
}
public Integer getPostImageId() {
return postImageId;
}
public void setPostImageId(Integer postImageId) {
this.postImageId = postImageId;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Post getPostId() {
return postId;
}
public void setPostId(Post postId) {
this.postId = postId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (postImageId != null ? postImageId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PostImage)) {
return false;
}
PostImage other = (PostImage) object;
if ((this.postImageId == null && other.postImageId != null) || (this.postImageId != null && !this.postImageId.equals(other.postImageId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.PostImage[ postImageId=" + postImageId + " ]";
}
}
i want to get collection of images for particular post like
Collection objPostImage = objPost.getPostImageCollection()
but manytoone relationship do not provide this functionality to me how can i convert it to one to many or how can i get Image Collection for a post.?
I am new to java so any help and suggestion will be appreciated
thanx in advance...
You can add a java.util.Set of PostImages in your Post object, and use the Hibernate mapping to provide the relationship. This site has a great example of setting up One to Many relationships.
So, for example, you would want to add something like the following to your Post class:
private Set<PostImage> postImages = new HashSet<PostImage>();
#OneToMany(fetch = FetchType.LAZY, mappedBy = "post")
public Set<PostImage> getPostImages() {
return this.postImages;
}
public void setPostImages(Set<PostImage> postImages) {
this.postImages= postImages;
}
Then, in your PostImage class, add a reference to a Post object:
private Post post;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "POST_ID", nullable = false)
public Stock getPost() {
return this.post;
}
public void setPost(Post post) {
this.post= post;
}
After adding that, you will be able to call the getPostImages() method on your Post object.
Try this:
#Entity
#Table(name = "post")
public class Post
{
//....
#OneToMany(mappedBy = "post")
private Set<PostImage> images;
//....
}
#Entity
#Table(name = "post_image")
public class PostImage
{
//....
#JoinColumn(name = "post_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Post post;
//....
}
The reason why Seth's answer didn't work is because EclipseLink uses fields to access persistence data. (Hibernate uses properties IIRC.) You can specify per class how a JPA provider should access this data.
Using fields:
#Entity
#Access(AccessType.FIELD)
public class SomeEntity
{
#Id
private Long id;
//....
}
Using properties:
#Entity
#Access(AccessType.PROPERTY)
public class SomeEntity
{
private Long id;
//....
#Id
public Long getId()
{
return id;
}
}
However when using #Access(AccessType.PROPERTY) fields are also used (at least in EclipseLink) so something like this is possible:
#Entity
#Access(AccessType.PROPERTY)
public class SomeEntity
{
private Long id;
#Column(name = "text")
private String someText;
//....
#Id
public Long getId()
{
return id;
}
}