Please can you help me? In JPA, I try to create a OneToMany bidirectional relation, but I have the following errors :
"[EclipseLink-63] : The instance creation method [entity.OrderLine.], with no parameters, does not exist, or is not accessible.
[EclipseLink-28019] : Deployment of PersistenceUnit [simple-jpaPU] failed. Close all factories for this PersistenceUnit."
There are my entities :
OneToMany Entity :
package entity;
import java.util.*;
import java.io.Serializable;
import javax.persistence.*;
import org.eclipse.persistence.annotations.TimeOfDay;
#Entity
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#OneToMany(mappedBy = "o")
private List<OrderLine> orderLines;
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public List<OrderLine> getOrderLines() {
return orderLines;
}
public void setOrderLines(ArrayList<OrderLine> orderLines) {
this.orderLines = orderLines;
}
public Order(Date creationDate) {
this.creationDate = creationDate;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "entity.Order[ id=" + id + " ]";
}
}
ManyToOne Entity :
package entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="orderline_table")
public class OrderLine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String item;
private Double unitPrice;
private Integer quantity;
#ManyToOne
Order o;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public Double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(Double unitPrice) {
this.unitPrice = unitPrice;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public OrderLine(String item, Double unitPrice, Integer quantity) {
this.item = item;
this.unitPrice = unitPrice;
this.quantity = quantity;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "entity.OrderLine[ id=" + id + " ]";
}
}
It fails because OrderLine does not have no-arg constructor. It is required as stated in JPA 2.1 specification (Chapter 2.1):
The entity class must have a no-arg constructor. The entity class may have other constructors as well.The no-arg constructor must be public or protected.
Default constructor is not generated because other constructor is given. Problem can be fixed by adding following constructor:
public OrderLine() {
}
Related
I have a requirement where I need to plan inside subset of data. For example, I have a stock of steel beams of certain grade. While planning I need to fit the available beams into stock only if they match the profile.
How do I do this with constraint streams. Any example would be appreciated.
I don't seem to get the hang around constraint streams.
I need to fit the ProjectMembers into StockMembers only if the profile matches.
Planning entity
#PlanningEntity
public class ProjectMember
extends AbstractPersistable
implements Labeled {
private int requiredLength; // in mm
private String profile;
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
private StockMember stockMember;
ProjectMember() {
}
public ProjectMember(long id, int requiredLength) {
super(id);
this.requiredLength = requiredLength;
}
public int getRequiredLength() {
return requiredLength;
}
public void setRequiredLength(int requiredLength) {
this.requiredLength = requiredLength;
}
#PlanningVariable
public StockMember getStockMember() {
return stockMember;
}
public void setStockMember(StockMember stockMember) {
this.stockMember = stockMember;
}
#Override
public String getLabel() {
return "Project Member " + id;
}
}
public class StockMember
extends AbstractPersistable
implements Labeled {
private int length; // in mm
private String profile;
private int cost; // in dollars
StockMember() {
}
public StockMember(long id, int length, int cost) {
super(id);
this.length = length;
this.cost = cost;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getProfile() {
return this.profile;
}
#Override
#JsonIgnore
public String getLabel() {
return "Stock Member " + id;
}
}
Planning solution
#PlanningSolution
public class NestMembers extends AbstractPersistable {
private List<StockMember> stockMemberList;
private List<ProjectMember> projectMemberList;
private HardSoftScore score;
NestMembers() {
}
public NestMembers(long id, List<StockMember> stockMemberList,
List<ProjectMember> projectMemberList) {
super(id);
this.stockMemberList = stockMemberList;
this.projectMemberList = projectMemberList;
}
#ValueRangeProvider
#ProblemFactCollectionProperty
public List<StockMember> getStockMemberList() {
return stockMemberList;
}
public void setStockMemberList(List<StockMember> computerList) {
this.stockMemberList = computerList;
}
#PlanningEntityCollectionProperty
public List<ProjectMember> getProjectMemberList() {
return projectMemberList;
}
public void setProjectMemberList(List<ProjectMember> projectMemberList)
{
this.projectMemberList = projectMemberList;
}
#PlanningScore
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
Constraint Provider
public class NestingConstraintProvider implements ConstraintProvider {
#Override
public Constraint[] defineConstraints(ConstraintFactory
constraintFactory) {
return new Constraint[]{
matchProfile(constraintFactory),
requiredLengthTotal(constraintFactory),
memberCost(constraintFactory)
};
}
Constraint requiredLengthTotal(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(ProjectMember.class)
.groupBy(ProjectMember::getStockMember,
sum(ProjectMember::getRequiredLength))
.filter((stockMember, requiredLength) -> requiredLength >
stockMember.getLength())
.penalize(HardSoftScore.ONE_HARD,
(stockMember, requiredLength) -> requiredLength -
stockMember.getLength())
.asConstraint("requiredLength");
}
Constraint matchProfile(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(ProjectMember.class)
.join(StockMember.class).
filter((projectMember, stockMember) ->
!projectMember.getProfile().equals(stockMember.getProfile()))
.penalize(HardSoftScore.ONE_HARD)
.asConstraint("requiredProfileMatch");
}
//
Constraint memberCost(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(StockMember.class)
.ifExists(ProjectMember.class, equal(Function.identity(),
ProjectMember::getStockMember))
.penalize(HardSoftScore.ONE_SOFT, StockMember::getCost)
.asConstraint("cost");
}
I wrote two controller class in spring application called player and team and I want join this model classes for connect sql database and I write code but it give me error so please help me to resolve that I'm sure problem happen in below two files and my other dependencies and database connection working well
my Team class
package com.withAngular.team;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.beans.factory.annotation.Autowired;
import com.withAngular.demo.player.Player;
#Entity
#Table(name = "team")
public class Team {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "team")
private String team;
#Column(name = "description")
private String description;
#Column(name = "owner")
private String owner;
#Column(name = "total_played")
private int totalPlayed;
#Column(name = "total_won")
private int totalWon;
#Column(name = "total_lost")
private int totalLost;
#Column(name = "no_result")
private int noResult;
#OneToMany
(mappedBy = "team", cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
private List<Player> players = new ArrayList<>();
public Team(int id, String name, String description, String owner, int totalplayed, int totalwon, int totallost, int noresult) {
this.setId(id);
this.setDescription(description);
this.setOwner(owner);
this.setTotalPlayed(totalplayed);
this.setTotalWon(totalwon);
this.setTotalLost(totallost);
this.setNoResult(noresult);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public List<Player> getPlayers() {
return players;
}
public void setPlayers(List<Player> players) {
this.players = players;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public int getTotalPlayed() {
return totalPlayed;
}
public void setTotalPlayed(int totalPlayed) {
this.totalPlayed = totalPlayed;
}
public int getTotalWon() {
return totalWon;
}
public void setTotalWon(int totalWon) {
this.totalWon = totalWon;
}
public int getTotalLost() {
return totalLost;
}
public void setTotalLost(int totalLost) {
this.totalLost = totalLost;
}
public int getNoResult() {
return noResult;
}
public void setNoResult(int noResult) {
this.noResult = noResult;
}
}
my Player class
package com.withAngular.demo.player;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.withAngular.team.Team;
#Entity
// #Table(name=PLAYER) when table name different from the class name
public class Player {
#Id // primary key
#GeneratedValue(strategy = GenerationType.AUTO) // auto increment
private int id;
// #Column(name = "PlayerName") when db table column name different from the
// property name assigned below
private String playerName;
private String preference;
#Column(name= "match_played")
private int matchPlayed;
private int runs;
private int wickets;
#Column(name= "highest_score")
private int highestScore;
#Column(name="best_wicket")
private String bestWicket;
private int fifties;
private int centuries;
private int thirties;
private int catches;
private int stumpings;
private int fours;
private int sixes;
#Column(name = "strike_rate")
private double strikeRate;
private double average;
#ManyToOne(targetEntity = Team.class)
#JoinColumn(name= "team_id")
private Team team;
// getters and setters
public Player(int id, String playername, String preference, int matchplayed, int runs, int wickets, int highestscore, String bestWicket, int fifties, int centuries, int thirties, int caches, int stumpings,int fours, int sixes, double strikerate, double average) {
// TODO Auto-generated constructor stub
this.setId(id);
this.setPlayerName(playername);
this.setPreference(preference);
this.setMatchPlayed(matchplayed);
this.setRuns(runs);
this.setWickets(wickets);
this.setHighestScore(highestscore);
this.setBestWicket(bestWicket);
this.setFifties(fifties);
this.setCenturies(centuries);
this.setThirties(thirties);
this.setCatches(caches);
this.setStumpings(stumpings);
this.setFours(fours);
this.setSixes(sixes);
this.setStrikeRate(strikerate);
this.setAverage(average);
}
public int getId() {
return id;
}
public String getPreference() {
return preference;
}
public void setPreference(String preference) {
this.preference = preference;
}
public int getMatchPlayed() {
return matchPlayed;
}
public void setMatchPlayed(int matchPlayed) {
this.matchPlayed = matchPlayed;
}
public int getRuns() {
return runs;
}
public void setRuns(int runs) {
this.runs = runs;
}
public int getWickets() {
return wickets;
}
public void setWickets(int wickets) {
this.wickets = wickets;
}
public int getHighestScore() {
return highestScore;
}
public void setHighestScore(int highestScore) {
this.highestScore = highestScore;
}
public String getBestWicket() {
return bestWicket;
}
public void setBestWicket(String bestWicket) {
this.bestWicket = bestWicket;
}
public int getFifties() {
return fifties;
}
public void setFifties(int fifties) {
this.fifties = fifties;
}
public int getCenturies() {
return centuries;
}
public void setCenturies(int centuries) {
this.centuries = centuries;
}
public int getThirties() {
return thirties;
}
public void setThirties(int thirties) {
this.thirties = thirties;
}
public int getCatches() {
return catches;
}
public void setCatches(int catches) {
this.catches = catches;
}
public int getStumpings() {
return stumpings;
}
public void setStumpings(int stumpings) {
this.stumpings = stumpings;
}
public int getFours() {
return fours;
}
public void setFours(int fours) {
this.fours = fours;
}
public int getSixes() {
return sixes;
}
public void setSixes(int sixes) {
this.sixes = sixes;
}
public double getStrikeRate() {
return strikeRate;
}
public void setStrikeRate(double strikeRate) {
this.strikeRate = strikeRate;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
public void setId(int id) {
this.id = id;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
}
and after run as spring boot app it give me below error
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.withAngular.demo.player.Player.team references an unknown entity: com.withAngular.team.Team
It is a very simple problem, You need to put both the entity classes in same package and that package should be either the package which holds the main application class that is annotated with
#SpringBootApplication
Or any of the sub package of parent package.
Eg: If package of your parent class is com.withAngular than put the Team and Player class also in the same package.
Change package com.withAngular.team; to package com.withAngular; in Team class.
Change package com.withAngular.demo.player; to package com.withAngular; in Player class.
Use the Annotation EnableJpaRepositories in your class annotated with #SpringBootApplication and set the
attribute basePackages to a common package.
So in your case com.withAngular.
#EnableJpaRepositories(basePackages="com.withAngular")
But it is better to moven entities in the same subpackage not in the "root" package of your application
Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type)
Am integrating room into my existing project. While annotating a POJO, which implements Parcelable, with #Entity tag and making necessary changes, am getting this error. I already have an empty constructor in it. Any help would be appreciated.
#Entity(tableName = "Departments")
public class Department implements Parcelable {
#PrimaryKey(autoGenerate = true)
private Integer primaryId;
private Integer id;
private String departmentName;
private String logoUrl;
#Embedded
private ArrayList<Template> templateList;
public Department() {
}
protected Department(Parcel in) {
this.primaryId = (Integer) in.readSerializable();
this.departmentName = in.readString();
this.logoUrl = in.readString();
this.id = (Integer) in.readSerializable();
this.templateList = in.createTypedArrayList(Template.CREATOR);
}
public static final Creator<Department> CREATOR = new Creator<Department>() {
#Override
public Department createFromParcel(Parcel in) {
return new Department(in);
}
#Override
public Department[] newArray(int size) {
return new Department[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(primaryId);
dest.writeString(departmentName);
dest.writeString(logoUrl);
dest.writeSerializable(id);
dest.writeTypedList(templateList);
}
public Integer getPrimaryId() {
return primaryId;
}
public void setPrimaryId(Integer primaryId) {
this.primaryId = primaryId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public ArrayList<Template> getTemplateList() {
return templateList;
}
public void setTemplateList(ArrayList<Template> templateList) {
this.templateList = templateList;
}
}
#Entity(tableName = "Templates")
public class Template implements Parcelable {
#PrimaryKey(autoGenerate = true)
private Integer primaryId;
private Integer id;
private String code;
private String description;
private Integer departmentId;
#Embedded
private ArrayList<Issue> issueList;
public Template() {
}
private Template(Parcel in) {
this.primaryId = (Integer) in.readSerializable();
this.code = in.readString();
this.description = in.readString();
this.id = (Integer) in.readSerializable();
this.departmentId = (Integer) in.readSerializable();
this.issueList = in.createTypedArrayList(Issue.CREATOR);
}
public static final Creator<Template> CREATOR = new Creator<Template>() {
#Override
public Template createFromParcel(Parcel in) {
return new Template(in);
}
#Override
public Template[] newArray(int size) {
return new Template[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(primaryId);
dest.writeString(code);
dest.writeString(description);
dest.writeSerializable(id);
dest.writeSerializable(departmentId);
dest.writeTypedList(issueList);
}
public Integer getPrimaryId() {
return primaryId;
}
public void setPrimaryId(Integer primaryId) {
this.primaryId = primaryId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList<Issue> getIssueList() {
return issueList;
}
public void setIssueList(ArrayList<Issue> issueList) {
this.issueList = issueList;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
}
#Entity(tableName = "Issues")
public class Issue implements Parcelable {
#PrimaryKey(autoGenerate = true)
private Integer primaryId;
private Integer id;
private String code;
private String description;
private Integer parentIssue;
public Issue() {
}
protected Issue(Parcel in) {
this.primaryId = (Integer) in.readSerializable();
this.code = in.readString();
this.description = in.readString();
this.id = (Integer) in.readSerializable();
this.parentIssue = (Integer) in.readSerializable();
}
public static final Creator<Issue> CREATOR = new Creator<Issue>() {
#Override
public Issue createFromParcel(Parcel in) {
return new Issue(in);
}
#Override
public Issue[] newArray(int size) {
return new Issue[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(primaryId);
dest.writeString(code);
dest.writeString(description);
dest.writeSerializable(id);
dest.writeSerializable(parentIssue);
}
public Integer getPrimaryId() {
return primaryId;
}
public void setPrimaryId(Integer primaryId) {
this.primaryId = primaryId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getParentIssue() {
return parentIssue;
}
public void setParentIssue(Integer parentIssue) {
this.parentIssue = parentIssue;
}
}
Room assumes your entity class will be having only one constructor. But there is no such limitations, If you have multiple constructor then annotate one of them with
#Ignore
Room will ignore this constructor and compile without any error.
Example
#Entity(tableName = "Departments")
public class Department implements Parcelable {
#PrimaryKey(autoGenerate = true)
private Integer primaryId;
private Integer id;
private String departmentName;
private String logoUrl;
#Embedded
private ArrayList<Template> templateList;
/**Room will ignore this constructor
**/
#Ignore
public Department() {
}
protected Department(Parcel in) {
this.primaryId = (Integer) in.readSerializable();
this.departmentName = in.readString();
this.logoUrl = in.readString();
this.id = (Integer) in.readSerializable();
this.templateList = in.createTypedArrayList(Template.CREATOR);
}
}
I'm not sure why you are getting your specific constructor error. That said your code will error from embedding the ArrayList. #Embedded is not meant to be used this way. #Embedded allows you to flatten your POJO structure when storing it. Nested POJO properties will appear as if they had been properties on the parent POJO. Using Embedded on a List is the same as asking it to flatten the properties of the ArrayList object and store them, not flatten the list items and store them.
The appropriate measure is to transition into a foreign key, primary key relationship. An alternative solution is to create a new POJO that contains your list of items (ie Templates, with an 's'). This would contain an ArrayList of Template objects. You would then define a converter that converts the POJO to a json/comma seperated list, and stores it in a single column that by default would be called "templates". Here is a link to this approach :
Android room persistent library - TypeConverter error of error: Cannot figure out how to save field to database"
Hope this helps.
Hello i have a RSSFEED with Maven and Jboss know i try to add Topics to a Newsfeed but i get this error:
14:02:43,526 WARN [com.arjuna.ats.arjuna] (default task-10) ARJUNA012125: TwoPhaseCoordinator.beforeCompletion - failed for SynchronizationImple< 0:ffffc0a80185:737c90a9:552bae74:4b, org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization#694357 >: javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of Topic.id
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl$CallbackExceptionMapperImpl.mapManagedFlushFailure(AbstractEntityManagerImpl.java:1882) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.engine.transaction.synchronization.internal.SynchronizationCallbackCoordinatorNonTrackingImpl.beforeCompletion(SynchronizationCallbackCoordinatorNonTrackingImpl.java:119) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization.beforeCompletion(RegisteredSynchronization.java:50) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
I try to have a #ManytoMany with my Topic.java and News.Java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
#Table(name = "Topic")
#Entity
public class Topic implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator="seq_topic")
#SequenceGenerator(name="seq_topic", sequenceName="seq_topic", allocationSize=1)
private int id;
private String name;
public int getId() {
return id;
}
#ManyToMany (fetch = FetchType.EAGER, mappedBy = "topic")
private List<News> News = new ArrayList<>();
public List<News> getNews() {
return News;
}
public void setNews(List<News> news) {
News = news;
}
public void setId(int id) {
this.id = id;
}
public Topic(){
}
public Topic(String name){
this.name =name;
}
public String getName() {
return name;
}
public void setName(String name) {
name = name;
}
#Override
public String toString() {
return name;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Topic other = (Topic) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Now I dont really now where ist the Problem because i Have a getter and Setter Methode !
Following this link
I would like to use OneToMany instead ManyToMany annotation, having middle class with composite key in it using Ebean. I have this error:
java.lang.RuntimeException: Error reading annotations for models.SoftwareTagPk
This is my SoftwareTagPk class:
#Embeddable
public class SoftwareTagPk implements Serializable {
#ManyToOne
private Tag tag;
#ManyToOne
private Software software;
...
}
And SoftwareTag class:
#Entity
public class SoftwareTag extends Model {
#EmbeddedId
private SoftwareTagPk pk = new SoftwareTagPk();
#Transient
public Tag getTag() {
return pk.getTag();
}
public void setTag(Tag aTag) {
pk.setTag(aTag);
}
#Transient
public Software getSoftware() {
return pk.getSoftware();
}
public void setSoftware(Software aSoftware) {
pk.setSoftware(aSoftware);
}
}
Also in logs:
Error with association to [class models.Tag] from
[models.SoftwareTagPk.tag]. Is class models.Tag registered?
How to fix it?
To make this code work you have to do:
In your SoftwareTagPk class put only id's of Tag and Software
Move #ManyToOne relations to SoftwareTag class
Add #JoinColumn annotations with attributes updatable and insertable set to false.
Override setters setTag and setSoftware in SoftwareTag class. In these setters you will rewrite id's to composite key.
Main idea of this solution is that SoftwareTag has composite key and #ManyToOne relations and they are mapped to the same collumns.
This is the code:
Tag.java
#Entity
public class Tag extends Model {
#Id
private Integer id;
#OneToMany(mappedBy="tag")
public List<SoftwareTag> softwareTags;
public Integer getId() {
return id;
}
public void setId(Integer aId) {
id=aId;
}
public static Finder<Integer,Tag> find = new Finder<Integer,Tag>(
Integer.class, Tag.class
);
}
Software.java
#Entity
public class Software extends Model {
#Id
private Integer id;
#OneToMany(mappedBy="software")
public List<SoftwareTag> softwareTags;
public Integer getId() {
return id;
}
public void setId(Integer aId) {
id=aId;
}
}
SoftwareTag.java
#Entity
public class SoftwareTag extends Model {
SoftwareTag() {
pk = new SoftwareTagPk();
}
#EmbeddedId
private SoftwareTagPk pk = new SoftwareTagPk();
#ManyToOne
#JoinColumn(name = "tag_id", insertable = false, updatable = false)
private Tag tag;
#ManyToOne
#JoinColumn(name = "software_id", insertable = false, updatable = false)
private Software software;
public Tag getTag() {
return tag;
}
public void setTag(Tag aTag) {
tag = aTag;
pk.tag_id = aTag.getId();
}
public Software getSoftware() {
return software;
}
public void setSoftware(Software aSoftware) {
software = aSoftware;
pk.software_id = aSoftware.getId();
}
}
SoftwareTagPk.java
#Embeddable
public class SoftwareTagPk implements Serializable {
public Integer tag_id;
public Integer software_id;
#Override
public int hashCode() {
return tag_id + software_id;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
SoftwareTagPk pk = (SoftwareTagPk)obj;
if(pk == null)
return false;
if (pk.tag_id.equals(tag_id) && pk.software_id.equals(software_id)) {
return true;
}
return false;
}
}