JPA many-to-many saves duplicate entities - java

I have difficulties with JPA many-to-many unidirectional relationship. The problem is that duplicate Label entities are created in DB even if they are the same. For performance reason the #Id is a generated number and not Label.label. The connected problem is that findByLabel() does not find the two notes.
I read many articles and examples and I think I have similar code, but it doesn't work. Any help is appreciated.
I'm using Spring Boot, H2, Spring Data JPA. I am looking for non-XML, pure Java annotation solution.
Repository:
public interface NoteRepository extends CrudRepository<Note, Long> {
#Query("SELECT a from Note a where ?1 member of a.labels")
List<Note> findByLabel(Label label); }
Label:
#Entity
public class Label {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "label_id")
private Long labelId;
private String label;
protected Label() {
}
public Label(String label) {
this.label = label;
}
public Long getLabelId() {
return labelId;
}
public void setLabelId(Long labelId) {
this.labelId = labelId;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Label)) return false;
Label label1 = (Label) o;
return getLabel().equals(label1.getLabel());
}
#Override
public int hashCode() {
return Objects.hash(getLabel());
}
#Override
public String toString() {
return "Label{" +
"labelId=" + labelId +
", label='" + label + '\'' +
'}';
}
}
Note:
#Entity
public class Note {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "note_id")
private Long noteId;
private String note;
#ManyToMany(
fetch = FetchType.EAGER,
cascade = CascadeType.ALL)
#JoinTable(
name = "Note_Label",
joinColumns = #JoinColumn(
name = "NoteId",
referencedColumnName = "note_id"),
inverseJoinColumns = #JoinColumn(
name = "LabelId",
referencedColumnName = "label_id"))
private Set<Label> labels;
protected Note() {
}
public Note(String note, Set<Label> labels) {
this.note = note;
this.labels = labels;
}
public Note(String note) {
this(note, null);
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Long getNoteId() {
return noteId;
}
public void setNoteId(Long noteId) {
this.noteId = noteId;
}
public Set<Label> getLabels() {
return labels;
}
public void setLabels(Set<Label> labels) {
this.labels = labels;
}
#Override
public String toString() {
return "Note{" +
"note='" + note + '\'' +
", labels='" + labels + '\'' +
'}';
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Note)) return false;
Note note1 = (Note) o;
if (!getNote().equals(note1.getNote())) return false;
return getLabels() != null ? getLabels().equals(note1.getLabels()) : note1.getLabels() == null;
}
#Override
public int hashCode() {
int result = getNote() != null ? getNote().hashCode() : 0;
result = 31 * result + (getLabels() != null ? getLabels().hashCode() : 0);
return result;
}
}
Test fails:
#SpringBootTest
#RunWith(SpringRunner.class)
public class NoteRepositoryTest {
#Autowired
private NoteRepository repository;
#Test
public void findByLabel() throws Exception {
String labelAString = "labelA";
Label labelA = new Label(labelAString);
Label labelA1 = new Label(labelAString);
Label labelB = new Label("labelB");
Label labelC = new Label("labelC");
Note note1 = new Note(
"note1", new HashSet<Label>(Arrays.asList(
labelA, labelB)));
Note note2 = new Note(
"note2", new HashSet<Label>(Arrays.asList(
labelA1, labelC)));
repository.deleteAll();
repository.save(note1);
repository.save(note2);
List<Note> actualNotes = repository.findByLabel(labelA);
System.out.println(actualNotes);
assertTrue(actualNotes.size() == 2);
assertTrue(actualNotes.containsAll(Arrays.asList(note1, note2)));
}
}

the right code:
#Test
public void saveAndGet() throws Exception {
String labelAString = "labelA";
Label labelA = new Label(labelAString);
Label labelA1 = new Label(labelAString);
Label labelB = new Label("labelB");
Label labelC = new Label("labelC");
repository.save(labelA);
System.out.println(labelA.getLabelId());
repository.save(labelB);
Iterable<Label> all = repository.findAll();
all.forEach(p ->{
System.out.println(p.getLabel());
System.out.println(p.getLabelId());
});
}

Related

How to manipulate data I got from textfield and populate to table column in JavaFX

I'm new to JavaFX, and I'm sorry if this sound stupid. I'm working on a desktop app to display data from the database. I'm using JPA Hibernate.
This is a database of contractors and contracts, by getting the startdate of contract and contract duration from input, I want to be able to calculate the end date and display it to the table.
I created the method to calculate endDate, by the adding the number of month to the start date, but the problem is how do I display it on the Table.
Look at controller class:
package energiadata.controller;
public class ActiveContractTabController {
private ObservableList<ActiveContractor> dataActive = FXCollections.observableArrayList();
#FXML
private VBox vBox;
#FXML
private TextField tfContractor;
#FXML
private TextField tfNatureOfContract;
#FXML
private TextField tfUser_dept;
#FXML
private TextField tfValue;
#FXML
private TextField tfValueRate;
#FXML
public DatePicker startDatePicker;
#FXML
public TextField tfContractDuration;
#FXML
private TextField tfremarks;
#FXML
private ChoiceBox<String> choiceBox;
#FXML
private Button addContractButton;
#FXML
private TextArea resultAreaActive;
#FXML
private TableView<ActiveContractor> activeContractTable;
#FXML
private TableColumn<ActiveContractor, Integer> idColumn;
#FXML
private TableColumn<ActiveContractor, String> contractorColumn;
#FXML
private TableColumn<ActiveContractor, String> natureOfContractColumn;
#FXML
private TableColumn<ActiveContractor, String> user_deptColumn;
#FXML
private TableColumn<ActiveContractor, Integer> valueNairaColumn;
#FXML
private TableColumn<ActiveContractor, Integer> valueDollarColumn;
#FXML
private TableColumn<ActiveContractor, LocalDate> start_dateColumn;
#FXML
private TableColumn<ActiveContractor, LocalDate> end_dateColumn;
#FXML
private TableColumn<ActiveContractor, String> contractTypeColumn;
#FXML
private TableColumn<ActiveContractor, String> remarksColumn;
#FXML
private Button allContractsButton;
#FXML
private Button updateButton;
#FXML
private Button deleteButton;
public void setupTableActive() {
idColumn.setCellValueFactory(cellData -> cellData.getValue().idAProperty().asObject());
contractorColumn.setCellValueFactory(cellData -> cellData.getValue().contractor());
natureOfContractColumn.setCellValueFactory(cellData -> cellData.getValue().natureOfContract());
user_deptColumn.setCellValueFactory(cellData -> cellData.getValue().user_dept());
valueNairaColumn.setCellValueFactory(cellData -> cellData.getValue().value().asObject());
valueDollarColumn.setCellValueFactory(cellData -> cellData.getValue().valueMain().asObject());
start_dateColumn.setCellValueFactory(cellData -> cellData.getValue().start_date());
end_dateColumn.setCellValueFactory(cellData -> cellData.getValue().end_date());
contractTypeColumn.setCellValueFactory(cellData -> cellData.getValue().contractType());
remarksColumn.setCellValueFactory(cellData -> cellData.getValue().remarks());
}
#FXML
void addButton(ActionEvent actionEvent) {
String contractor = tfContractor.getText();
String natureOfContract = tfNatureOfContract.getText();
String user_dept = tfUser_dept.getText();
Integer value = Integer.parseInt(tfValue.getText());
Integer valueRate = Integer.parseInt(tfValueRate.getText());
LocalDate start_date = startDatePicker.getValue();
Integer contractDuration = Integer.parseInt(tfContractDuration.getText());
String contractType = choiceBox.getValue();
String remarks = tfremarks.getText();
ActiveContractor activeContractor = new ActiveContractor(contractor, natureOfContract, user_dept, value, valueRate, start_date, contractDuration, remarks, contractType);
try {
activeContractTable.getItems().add(activeContractor);
DBUtil.saveActiveContractor(activeContractor);
resultAreaActive.setText("Active Contract Added");
} catch (Exception e) {
resultAreaActive.setText("Error adding active contract" + e);
}
}
#FXML
void deleteActiveContractor(ActionEvent actionEvent) {
activeContractTable.getItems().remove(activeContractTable.getSelectionModel().getSelectedItem());
DBUtil.removeActiveContractor(activeContractTable.getSelectionModel().getSelectedItem());
resultAreaActive.setText(" Contractor Deleted! ");
}
#FXML
void updateActiveContractorDetails(ActionEvent actionEvent) {
ActiveContractor activeContractor = activeContractTable.getSelectionModel().getSelectedItem();
String _contractor = tfContractor.getText();
String _natureOfContract = tfNatureOfContract.getText();
String _user_dept = tfUser_dept.getText();
Integer _value = Integer.parseInt(tfValue.getText());
Integer _valueRate = Integer.parseInt(tfValueRate.getText());
LocalDate _start_date = startDatePicker.getValue();
Integer _contractDuration = Integer.parseInt(tfContractDuration.getText());
String _remarks = tfremarks.getText();
try {
DBUtil.updateActiveContractor(activeContractor);
activeContractTable.getItems().add(activeContractor);
activeContractTable.toFront();
resultAreaActive.setText(_contractor + "updated Successfully!");
} catch (Exception e) {
resultAreaActive.setText("Could not update the Database" + e);
}
}
#FXML
void getActiveContractorList(ActionEvent actionEvent) {
EntityManager em = DBUtil.getEntityManager();
List<ActiveContractor> list = em.createQuery("SELECT a FROM ActiveContractor a", ActiveContractor.class).getResultList();
if (dataActive == null) {
dataActive = FXCollections.observableArrayList(list);
} else {
dataActive.clear();
dataActive.addAll(list);
}
activeContractTable.setItems(dataActive);
// contractorTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
setupTableActive();
resultAreaActive.setText(" List Display! ");
}
ActiveContractor activeContract;
public LocalDate changeEndDateProperty() {
LocalDate localdate = startDatePicker.getValue();
LocalDate end_localDate = localdate.plusMonths(Long.valueOf(tfContractDuration.getText()));
return end_localDate;
}
public Integer valueRateCal() {
Integer valueMainDollar = Integer.parseInt(tfValue.getText())
* Integer.parseInt(tfValueRate.getText());
return valueMainDollar;
}
#FXML
public void initialize() {
setupTableActive();
choiceBox.setItems(FXCollections.observableArrayList("One-Off", "Running"));
}
}
And Entity Class:
package energiadata.model;
public class ActiveContractor implements Externalizable {
private static final long serialVersionUID = 1L;
private IntegerProperty idA;
private int _idA;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Basic(optional = false)
#Column(name = "id")
public final int getId() {
if (idA == null) {
return _idA;
} else {
return idA.get();
}
}
public final void setId(int id) {
if (this.idA == null) {
_idA = id;
} else {
this.idA.set(id);
}
}
public IntegerProperty idAProperty() {
if (idA == null) {
idA = new SimpleIntegerProperty(this, "id", _idA);
}
return idA;
}
private StringProperty contractor;
private String _contractor;
#Basic(optional = false)
#Column(name = "contractor")
public final String getContractor() {
if (this.contractor == null) {
return _contractor;
} else {
return contractor.get();
}
}
public final void setContractor(String contractor) {
if (this.contractor == null) {
_contractor = contractor;
} else {
this.contractor.set(contractor);
}
}
public StringProperty contractor() {
if (contractor == null) {
contractor = new SimpleStringProperty(this, "contractor", _contractor);
}
return contractor;
}
private StringProperty natureOfContract;
private String _natureOfContract;
#Basic(optional = false)
#Column(name = "natureOfContract")
public final String getNatureOfContract() {
if (this.natureOfContract == null) {
return _natureOfContract;
} else {
return natureOfContract.get();
}
}
public final void setNatureOfContract(String natureOfContract) {
if (this.natureOfContract == null) {
_natureOfContract = natureOfContract;
} else {
this.natureOfContract.set(natureOfContract);
}
}
public StringProperty natureOfContract() {
if (natureOfContract == null) {
natureOfContract = new SimpleStringProperty(this, "natureOfContract", _natureOfContract);
}
return natureOfContract;
}
private StringProperty user_dept;
private String _user_dept;
#Basic(optional = false)
#Column(name = "user_dept")
public final String getUser_dept() {
if (this.user_dept == null) {
return _user_dept;
} else {
return user_dept.get();
}
}
public final void setUser_dept(String user_dept) {
if (this.user_dept == null) {
_user_dept = user_dept;
} else {
this.user_dept.set(user_dept);
}
}
public StringProperty user_dept() {
if (user_dept == null) {
user_dept = new SimpleStringProperty(this, "user_dept", _user_dept);
}
return user_dept;
}
private IntegerProperty value;
private int _value;
#Basic(optional = false)
#Column(name = "value")
public final Integer getValue() {
if (this.value == null) {
return _value;
} else {
return value.get();
}
}
public final void setValue(Integer value) {
if (this.value == null) {
_value = value;
} else {
this.value.set(value);
}
}
public IntegerProperty value() {
if (value == null) {
value = new SimpleIntegerProperty(this, "value", _value);
}
return value;
}
private IntegerProperty valueMain;
private Integer _valueMain;
#Basic(optional = false)
#Column(name = "valueMain")
public final Integer getValueMain() {
if (this.valueMain == null) {
return _valueMain;
} else {
return valueMain.get();
}
}
public final void setValueMain(Integer valueMain) {
if (this.valueMain == null) {
_valueMain = valueMain;
} else {
this.value.set(valueMain);
}
}
public IntegerProperty valueMain() {
if (valueMain == null) {
valueMain = new SimpleIntegerProperty(this, "valueMain", _valueMain);
}
return valueMain;
}
private IntegerProperty valueRate;
private int _valueRate;
#Basic(optional = false)
#Column(name = "valueRate")
public final Integer getValueRate() {
if (this.valueRate == null) {
return _valueRate;
} else {
return valueRate.get();
}
}
public final void setValueRate(Integer valueRate) {
if (this.valueRate == null) {
_valueMain = valueRate;
} else {
this.value.set(valueRate);
}
}
public IntegerProperty valueRate() {
if (valueMain == null) {
valueMain = new SimpleIntegerProperty(this, "valueMain", _valueRate);
}
return valueRate;
}
private SimpleObjectProperty<LocalDate> start_date;
private LocalDate _start_date;
#Basic(optional = false)
#Column(name = "start_date")
public final LocalDate getStart_date() {
if (this.start_date == null) {
return _start_date;
} else {
return start_date.get();
}
}
public final void setStart_date(LocalDate start_date) {
if (this.start_date == null) {
_start_date = start_date;
} else {
this.start_date.set(start_date);
}
}
public SimpleObjectProperty start_date() {
if (start_date == null) {
start_date = new SimpleObjectProperty<>(this, "start_date", _start_date);
}
return start_date;
}
private ObjectProperty<LocalDate> end_date;
private LocalDate _end_date;
#Basic(optional = false)
#Column(name = "end_date")
public final LocalDate getEnd_date() {
if (this.end_date == null) {
return _end_date;
} else {
return end_date.get();
}
}
public final void setEnd_date(LocalDate end_date) {
if (this.end_date == null) {
_end_date = end_date;
} else {
this.end_date.set(end_date);
}
}
public ObjectProperty end_date() {
if (end_date == null) {
end_date = new SimpleObjectProperty<>(this, "end_date", _end_date);
}
return end_date;
}
private IntegerProperty contractDuration;
private Integer _contractDuration;
#Basic(optional = false)
#Column(name = "contractDuration")
public final Integer getContractDuration() {
if (this.contractDuration == null) {
return _contractDuration;
} else {
return contractDuration.get();
}
}
public final void setContractDuration(Integer contractDuration) {
if (this.contractDuration == null) {
_contractDuration = contractDuration;
} else {
this.value.set(contractDuration);
}
}
public IntegerProperty contractDuration() {
if (contractDuration == null) {
contractDuration = new SimpleIntegerProperty(this, "contractDuration", _contractDuration);
}
return contractDuration;
}
private StringProperty remarks;
private String _remarks;
#Basic(optional = false)
#Column(name = "remarks")
public final String getRemarks() {
if (this.remarks == null) {
return _remarks;
} else {
return remarks.get();
}
}
public final void setRemarks(String remarks) {
if (this.remarks == null) {
_remarks = remarks;
} else {
this.remarks.set(remarks);
}
}
public StringProperty remarks() {
if (remarks == null) {
remarks = new SimpleStringProperty(this, "remarks", _remarks);
}
return remarks;
}
private StringProperty contractType;
private String _contractType;
#Basic(optional = false)
#Column(name = "contractType")
public final String getContractType() {
if (this.contractType == null) {
return _contractType;
} else {
return contractType.get();
}
}
public final void setContractType(String contractType) {
if (this.contractType == null) {
_contractType = contractType;
} else {
this.contractType.set(contractType);
}
}
public StringProperty contractType() {
if (contractType == null) {
contractType = new SimpleStringProperty(this, "contractType", _contractType);
}
return contractType;
}
public ActiveContractor() {
}
public ActiveContractor(String _contractor, String _natureOfContract, String _user_dept, int _value, int _valueRate, LocalDate _start_date, Integer _contractDuration, String _remarks, String _contractType) {
this._contractor = _contractor;
this._natureOfContract = _natureOfContract;
this._user_dept = _user_dept;
this._value = _value;
this._valueRate = _valueRate;
this._start_date = _start_date;
this._contractDuration = _contractDuration;
this._remarks = _remarks;
this._contractType = _contractType;
}
public ActiveContractor(StringProperty contractor, StringProperty natureOfContract, StringProperty user_dept, IntegerProperty value, IntegerProperty valueRate, SimpleObjectProperty<LocalDate> start_date, IntegerProperty contractDuration, StringProperty remarks, StringProperty contractType) {
this.contractor = contractor;
this.natureOfContract = natureOfContract;
this.user_dept = user_dept;
this.value = value;
this.valueRate = valueRate;
this.start_date = start_date;
this.contractDuration = contractDuration;
this.remarks = remarks;
this.contractType = contractType;
}
#Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(getId());
out.writeObject(getContractor());
out.writeObject(getNatureOfContract());
out.writeObject(getUser_dept());
out.writeObject(getValue());
out.writeObject(getValueMain());
out.writeObject(getValueRate());
out.writeObject(getStart_date());
out.writeObject(getEnd_date());
out.writeObject(getContractDuration());
out.writeObject(getRemarks());
out.writeObject(contractType());
}
#Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
setId(in.readInt());
setContractor((String) in.readObject());
setNatureOfContract((String) in.readObject());
setUser_dept((String) in.readObject());
setValue((Integer) in.readObject());
setValueMain((Integer) in.readObject());
setValueRate((Integer) in.readObject());
setStart_date((LocalDate) in.readObject());
setEnd_date((LocalDate) in.readObject());
setContractDuration((Integer) in.readObject());
setRemarks((String) in.readObject());
setContractType((String) in.readObject());
}
}
Since the Methods in not the Entity, I couldn't add it to the column... I've been on this for days.
My question is different from How can I add rows and columns to a JavaFX 8 TableView.
I already add columns to my tableview, check my setupTableActive() method above. What I'm trying to do is, for example, the end_dateColumn, I want to be able to get value fron DatePicker and add some months to it, then set it to the end_dateColumn. But by default, it only allows me to put Property method in the entity class there. Hope this is clear enough...
Ok, I see a lot happening here that needs a bit of work, but lets just look at your issue and you can sort the rest out yourself. From what I can tell it looks like you dont ever pass your end_date to the activeContractTable TableView and therefore the end_date will never be added to the Table no matter how hard you try, but you can fix this quite easily by adding and adjusting several lines of code as shown below:
Note my comments starting with //======
In the ActiveContractTabController class addButton method:
#FXML
void addButton(ActionEvent actionEvent) {
String contractor = tfContractor.getText();
String natureOfContract = tfNatureOfContract.getText();
String user_dept = tfUser_dept.getText();
Integer value = Integer.parseInt(tfValue.getText());
Integer valueRate = Integer.parseInt(tfValueRate.getText());
LocalDate start_date = startDatePicker.getValue();
//====== You need to add the end date here =====//
LocalDate end_date = changeEndDateProperty();
Integer contractDuration = Integer.parseInt(tfContractDuration.getText());
String contractType = choiceBox.getValue();
String remarks = tfremarks.getText();
//====== You need to add the end date to the line below, and modify ActiveContractor to receive the extra end_date variable =====//
ActiveContractor activeContractor = new ActiveContractor(contractor, natureOfContract, user_dept, value, valueRate, start_date, end_date, contractDuration, remarks, contractType);
In the ActiveContractor class:
//====== You need to add the end date to the line below as one of this methods inputs so it accepts the call from ActiveContractTabController =====//
public ActiveContractor(String _contractor, String _natureOfContract, String _user_dept, int _value, int _valueRate, LocalDate _start_date, LocalDate _end_date, Integer _contractDuration, String _remarks, String _contractType) {
this._contractor = _contractor;
this._natureOfContract = _natureOfContract;
this._user_dept = _user_dept;
this._value = _value;
this._valueRate = _valueRate;
this._start_date = _start_date;
//====== You need to add the end date here =====//
this._end_date = _end_date;
this._contractDuration = _contractDuration;
this._remarks = _remarks;
this._contractType = _contractType;
}
//====== You need to add the end date to the line below as one of this methods inputs so it accepts the call from ActiveContractTabController =====//
public ActiveContractor(StringProperty contractor, StringProperty natureOfContract, StringProperty user_dept, IntegerProperty value, IntegerProperty valueRate, SimpleObjectProperty<LocalDate> start_date, SimpleObjectProperty<LocalDate> end_date, IntegerProperty contractDuration, StringProperty remarks, StringProperty contractType) {
this.contractor = contractor;
this.natureOfContract = natureOfContract;
this.user_dept = user_dept;
this.value = value;
this.valueRate = valueRate;
this.start_date = start_date;
//====== You need to add the end date here =====//
this.end_date = end_date;
this.contractDuration = contractDuration;
this.remarks = remarks;
this.contractType = contractType;
}
I have not tested or checked this code, so you may need to make other adjustments for it to work as intended, but it should give you an idea.

Mapping issue on Hibernate

I am in the middle of developing a JHipster project and I've come to a halt due to what I believe to be mapping issues
My Database has several tables, but the two that affect me here are Study and Publication, where they have a Many to Many relationship.
I need to retrieve the collection of Publications where a study can be published, hence Study is the owner of the relationship, but for some reason, Hibernate don't recognise the attributes I map the relation with.
All of this started trying to solve a lazy connection issue, yes I have been through most posts relating this and I have tried everything that made sense to me.
Here the code of Study:
#Audited
#Entity
#Table(name = "Study")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "study")
public class Study implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "num_sites")
private Integer numSites;
#Column(name = "ref")
private String ref;
#Column(name = "study_type")
private String studyType;
#ManyToMany(fetch = FetchType.LAZY)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#JoinTable(name = "Pub_Study",
joinColumns = #JoinColumn(name="studies_id", referencedColumnName="id"),
inverseJoinColumns = #JoinColumn(name="publications_id", referencedColumnName="id"))
public static Set<Publication> publications = new HashSet<>();
#OneToMany(mappedBy = "study")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<SiteData> siteDatas = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getNumSites() {
return numSites;
}
public void setNumSites(Integer numSites) {
this.numSites = numSites;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public String getStudyType() {
return studyType;
}
public void setStudyType(String studyType) {
this.studyType = studyType;
}
public static Set<Publication> getPublicationss() {
return publications;
}
public void setPublicationss(Set<Publication> publications) {
this.publications = publications;
}
public Set<SiteData> getSiteDatas() {
return siteDatas;
}
public void setSiteDatas(Set<SiteData> siteDatas) {
this.siteDatas = siteDatas;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Study study = (Study) o;
if(study.id == null || id == null) {
return false;
}
return Objects.equals(id, study.id);
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "Study{" +
"id=" + id +
", numSites='" + numSites + "'" +
", ref='" + ref + "'" +
", studyType='" + studyType + "'" +
'}';
}
Here the code of Publication:
#Audited
#Entity
#Table(name = "Publication")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "publication")
public class Publication implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "authors")
private String authors;
#Column(name = "first_author")
private String firstAuthor;
#Column(name = "journal")
private String journal;
#Column(name = "pubMedId")
private Integer pubMedId;
#Column(name = "title")
private String title;
#Column(name = "year_publish")
private Integer yearPublish;
#Version
Integer version;
#ManyToMany(fetch = FetchType.LAZY)
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Study> studies = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getFirstAuthor() {
return firstAuthor;
}
public void setFirstAuthor(String firstAuthor) {
this.firstAuthor = firstAuthor;
}
public String getJournal() {
return journal;
}
public void setJournal(String journal) {
this.journal = journal;
}
public Integer getPubMedId() {
return pubMedId;
}
public void setPubMedId(Integer pubMedId) {
this.pubMedId = pubMedId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getYearPublish() {
return yearPublish;
}
public void setYearPublish(Integer yearPublish) {
this.yearPublish = yearPublish;
}
public Set<Study> getStudies() {
return studies;
}
public void setStudies(Set<Study> studys) {
this.studies = studys;
}
public Integer getVersion(){
return version;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Publication publication = (Publication) o;
if(publication.id == null || id == null) {
return false;
}
return Objects.equals(id, publication.id);
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "Publication{" +
"id=" + id +
", authors='" + authors + "'" +
", firstAuthor='" + firstAuthor + "'" +
", journal='" + journal + "'" +
", pubMedId='" + pubMedId + "'" +
", title='" + title + "'" +
", yearPublish='" + yearPublish + "'" +
'}';
}
}
Here the Implementation of the query from the Repository package:
public class SiteDataRepositoryImpl implements SiteDataRepositoryCustom{
#PersistenceContext
private EntityManager em;
#Override
public List <SiteDataViewDTO> searchSiteDataByFilter(List<Filter> listFilters) {
TypedQuery<SiteData> query = buildQuery(listFilters);
Hibernate.initialize(Study.publications);
int count=0;
for (Filter filter: listFilters){
if("country".equals(filter.getName()))
query.setParameter(filter.getName(), filter.getQuery());
else if("category".equals(filter.getName()))
query.setParameter(filter.getName(), filter.getQuery());
else if("studyRef".equals(filter.getName()))
query.setParameter(filter.getName(), filter.getQuery());
else if("studyType".equals(filter.getName()))
query.setParameter(filter.getName(), filter.getQuery());
else if("pubMedId".equals(filter.getName()))
query.setParameter(filter.getName(), Integer.valueOf(filter.getQuery()));
count++;
}
List<SiteData> siteDataList = query.getResultList();
List<SiteDataViewDTO> siteDataViewDTOList=new ArrayList<SiteDataViewDTO>();
//temp variables
List<String>tempListTreatments = new ArrayList<String>();
List<String>tempListTitles = new ArrayList<String>();
List<Integer>tempListIdMed = new ArrayList<Integer>();
//filling SiteDataViewDTO list
siteDataList.stream().forEach(sd->{
SiteDataViewDTO temp = new SiteDataViewDTO();
temp.setTypeStudy(sd.getTypeStudy() + "id SiteData: " + sd.getId());
temp.setRef(sd.getStudy().getRef());
temp.setCategory(sd.getCategory().getName());
temp.setUpper95CI(sd.getUpper95CI());
temp.setYearStart(sd.getYearStart());
temp.setYearEnd(sd.getYearEnd());
Set<Publication>setPu = sd.getStudy().getPublicationss();
System.out.println("#################### In the query, size of the Publications List "+setPu.size());
setPu.stream().forEach(sp-> {
tempListTitles.add(sp.getTitle());
tempListIdMed.add(sp.getPubMedId());
});
Set<Treatment>setTr = sd.getTreatments();
/*setTr.stream().forEach(sp-> {
tempListTreatments.add(sp.getTreatmentName());
});*/
temp.setListPubObject(setPu);
temp.setListTreatObject(setTr);
siteDataViewDTOList.add(temp);
});
return siteDataViewDTOList;
}
private TypedQuery<SiteData> buildQuery(List<Filter> listFilters){
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<SiteData> cq = cb.createQuery(SiteData.class);
Root<SiteData> siteData = cq.from(SiteData.class);
Join<SiteData, Category> cat = siteData.join("category", JoinType.LEFT);
Join<SiteData, Location> loc = siteData.join("location",JoinType.LEFT);
Join<SiteData, Treatment> tre = siteData.join("treatments",JoinType.LEFT);
Join<SiteData, Study> stu = siteData.join("study",JoinType.LEFT);
Join<Study, Publication> pub = stu.join("publications",JoinType.LEFT);
List<Predicate> predicates = new ArrayList<>();
int index = 0;
for(Filter filter : listFilters){
if("country".equals(filter.getName()))
predicates.add(cb.equal(loc.get("country"), cb.parameter(String.class, filter.getName())));
else if("category".equals(filter.getName()))
predicates.add(cb.equal(cat.get("name"), cb.parameter(String.class, filter.getName())));
else if("studyRef".equals(filter.getName()))
predicates.add(cb.equal(stu.get("ref"), cb.parameter(String.class, filter.getName())));
else if("studyType".equals(filter.getName()))
predicates.add(cb.equal(stu.get("studyType"), cb.parameter(String.class, filter.getName())));
else if("pubMedId".equals(filter.getName()))
predicates.add(cb.equal(pub.get("pubMedId"), cb.parameter(Integer.class, filter.getName())));
index++;
}
cq.where(cb.and(predicates.toArray(new Predicate[0])));
return em.createQuery(cq);
}
}
So, if anyone could throw some light on to this, it would be very helpful!
I Edit to add the main exception it throws:
Caused by: org.hibernate.QueryException: could not resolve property: publications of: org.wwarn.vivax.manager.domain.Study
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1978)
at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:367)
You have a typo in your entity definition: "publicationss" instead of "publications". Since Hibernate uses JavaBeans properties for data access, it complains about getPublications() loss in your definition.
Metamodel preserves you from such typos, consider using it.

JPQL createQuery is incompatible with query return type Collection

I want to get my profile in class Tournee (profil_tournee) list based on my tours ("tournee"). However, I have an exception. Can anyone help me?
Exception in thread "AWT-EventQueue-0"
java.lang.IllegalArgumentException: Type specified for TypedQuery
[fr.galettedebroons.domain.Profil] is incompatible with query return
type [interface java.util.Collection]
Request:
List<List<Profil>> listProfil = Arrays.asList(manager_.createQuery("select t.profil_tournee "
+ "FROM Tournee t WHERE t.nom LIKE :tournee", Profil.class)
.setParameter("tournee", tournee)
.getResultList());
Model :
#Entity
public class Tournee {
private int id;
private String nom;
private boolean lundi = false;
private boolean mardi = false;
private boolean mercredi = false;
private boolean jeudi = false;
private boolean vendredi = false;
private boolean samedi = false;
private boolean dimanche = false;
private List<Profil> profil_tournee;
public Tournee(){}
public Tournee(String nom, boolean lundi, boolean mardi, boolean mercredi, boolean jeudi,
boolean vendredi, boolean samedi, boolean dimanche, List<Profil> profil_tournee) {
this.nom = nom;
this.lundi = lundi;
this.mardi = mardi;
this.mercredi = mercredi;
this.jeudi = jeudi;
this.vendredi = vendredi;
this.samedi = samedi;
this.dimanche = dimanche;
this.profil_tournee = profil_tournee;
}
public Tournee(String nom, boolean lundi, boolean mardi, boolean mercredi, boolean jeudi,
boolean vendredi, boolean samedi, boolean dimanche) {
this.nom = nom;
this.lundi = lundi;
this.mardi = mardi;
this.mercredi = mercredi;
this.jeudi = jeudi;
this.vendredi = vendredi;
this.samedi = samedi;
this.dimanche = dimanche;
}
#Id #GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id_tournee) {
this.id = id_tournee;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public boolean isLundi() {
return lundi;
}
public void setLundi(boolean lundi) {
this.lundi = lundi;
}
public boolean isMardi() {
return mardi;
}
public void setMardi(boolean mardi) {
this.mardi = mardi;
}
public boolean isMercredi() {
return mercredi;
}
public void setMercredi(boolean mercredi) {
this.mercredi = mercredi;
}
public boolean isJeudi() {
return jeudi;
}
public void setJeudi(boolean jeudi) {
this.jeudi = jeudi;
}
public boolean isVendredi() {
return vendredi;
}
public void setVendredi(boolean vendredi) {
this.vendredi = vendredi;
}
public boolean isSamedi() {
return samedi;
}
public void setSamedi(boolean samedi) {
this.samedi = samedi;
}
public boolean isDimanche() {
return dimanche;
}
public void setDimanche(boolean dimanche) {
this.dimanche = dimanche;
}
#OneToMany(mappedBy="profil_tournee", cascade=CascadeType.PERSIST)
public List<Profil> getProfil_tournee() {
return profil_tournee;
}
public void setProfil_tournee(List<Profil> profil_tournee) {
this.profil_tournee = profil_tournee;
}
}
#Entity
public class Profil {
private String code_client;
private Client client_profil;
private Gamme gamme_profil;
private List<Livraison> livraison_profil;
private Boolean actif;
private Tournee profil_tournee;
private List<MargeLivraison> marge_profil;
private List<Prevision> prevision_profil;
public Profil(){}
public Profil(Gamme code_gamme, List<Livraison> livraison, Boolean actif) {
this.gamme_profil = code_gamme;
this.livraison_profil = livraison;
this.actif = actif;
}
#Id
public String getCode_client() {
return code_client;
}
public void setCode_client(String code_client) {
this.code_client = code_client;
}
public Boolean getActif() {
return actif;
}
public void setActif(Boolean actif) {
this.actif = actif;
}
#ManyToOne
public Gamme getGamme_profil() {
return gamme_profil;
}
public void setGamme_profil(Gamme gamme_profil) {
this.gamme_profil = gamme_profil;
}
#OneToMany(mappedBy="livraison_profil", cascade=CascadeType.PERSIST)
public List<Livraison> getLivraison_profil() {
return livraison_profil;
}
public void setLivraison_profil(List<Livraison> livraison_profil) {
this.livraison_profil = livraison_profil;
}
#ManyToOne
public Client getClient_profil() {
return client_profil;
}
public void setClient_profil(Client client) {
this.client_profil = client;
}
#ManyToOne
public Tournee getProfil_tournee() {
return profil_tournee;
}
public void setProfil_tournee(Tournee profil_tournee) {
this.profil_tournee = profil_tournee;
}
#OneToMany(mappedBy="marge_profil", cascade=CascadeType.PERSIST)
public List<MargeLivraison> getMarge_profil() {
return marge_profil;
}
public void setMarge_profil(List<MargeLivraison> marge_profil) {
this.marge_profil = marge_profil;
}
#OneToMany(mappedBy="prevision_profil", cascade=CascadeType.PERSIST)
public List<Prevision> getPrevision_profil() {
return prevision_profil;
}
public void setPrevision_profil(List<Prevision> prevision_profil) {
this.prevision_profil = prevision_profil;
}
Your expected result list will contain elements that are list of profiles, not profiles.
I would replace Profil.class by List.class for the Query creation :
List<List<Profil>> listProfil = Arrays.asList(manager_.createQuery("select t.profil_tournee "
+ "FROM Tournee t WHERE t.nom LIKE :tournee", List.class)
.setParameter("tournee", tournee)
.getResultList());
Your error gives you a hint that the returning type should be consistent with declared type when invoking EntityManager.createQuery(query, Type) method:
List<SomeType> em.createQuery("SELECT s FROM SomeType", SomeType.class);
However your real problem is that your query is illegal. In JPA collection-valued expressions cannot be part of SELECT clause. Please see another answer of mine https://stackoverflow.com/a/25890863/3796586.
The solution in your case would be to reverse the query like this:
List<Profil> result = em.createQuery("SELECT p FROM Profil p WHERE" +
"p.profil_tournee.norm LIKE :tournee", Profil.class)
.setParameter("tournee", tournee)
.getResultList());

JPA not merging neither flushing my entity

I'm facing a trouble where I've my transactions controlled by Spring Tx and when I do a merge and after flush, my implementation does not print the command neither the Spring Tx commit them.
Follows my code:
#Named
#Transactional(propagation = Propagation.MANDATORY, readOnly = false)
class AverbacaoDAOImpl extends AbstractDAOImpl<Averbacao, Long> implements AverbacaoDAO{
private List<Averbacao> atualizarAverbacoes(final List<Averbacao> averbacoes, final EtapaAverbacao etapa) {
int counter = 0;
for(Averbacao averbacao : averbacoes) {
averbacao.setEtapa(etapa);
atualizar(averbacao);
counter += 1;
}
entityManager.flush();
LOGGER.debug("Atualizado {} averbacoes para a etapa {}", counter, etapa);
return averbacoes;
}
}
private atualizar(Averbacao averbacao) {
entityManager.merge(averbacao);
}
Every objects in the list are managed by JPA (or I think that they're)
Follows logs:
Spring Transaction/Hibernate:
08:37:06,102 DEBUG [BilhetagemProcessManagerExecutor-1hread] [AbstractFlushingEventListener] Processing flush-time cascades
08:37:07,576 DEBUG [BilhetagemProcessManagerExecutor-1hread] [AbstractFlushingEventListener] Dirty checking collections
08:37:08,703 DEBUG [BilhetagemProcessManagerExecutor-1hread] [Collections] Collection found: [br.com.company.bilhetagem.brms.model.Proposta.propostaTaxaAplicaveis#35340], was: [br.com.company.bilhetagem.brms.model.Proposta.propostaTaxaAplicaveis#35340] (initialized)
08:37:08,706 DEBUG [BilhetagemProcessManagerExecutor-1hread] [AbstractFlushingEventListener] Flushed: 0 insertions, 0 updates, 0 deletions to 26047 objects
08:37:08,707 DEBUG [BilhetagemProcessManagerExecutor-1hread] [AbstractFlushingEventListener] Flushed: 0 (re)creations, 0 updates, 0 removals to 1 collections
08:37:08,707 DEBUG [BilhetagemProcessManagerExecutor-1hread] [EntityPrinter] Listing entities:
08:37:08,707 DEBUG [BilhetagemProcessManagerExecutor-1hread] [EntityPrinter] br.com.company.bilhetagem.brms.model.tarifas.TipoTarifaPercentual{percentualMultiplicador=1.0, tipo=OCD}
08:37:08,713 DEBUG [BilhetagemProcessManagerExecutor-1hread] [EntityPrinter] More......
Averbacao
#Entity
#Table(name = "TBIL_RELAC_AVERB_PROPT", schema = "BILHET")
#SecondaryTable(name = "TBIL_AVERBACAO", schema = "BILHET", pkJoinColumns = { #PrimaryKeyJoinColumn(name = "SEQ_NUMER_AVB") })
public final class Averbacao implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3229114271975034004L;
#Id
#Column(name = "SEQ_NUMER_AVB")
private long numeroAverbacao;
#ManyToOne(optional = false, targetEntity = Proposta.class)
#JoinColumn(name = "SEQ_NUMER_PRS", nullable = false)
private Proposta proposta;
#Column(name = "VLR_IS", scale = 15, precision = 2, nullable = true)
private Double valorIS;
#ManyToOne(optional = false)
#JoinColumn(name = "CTL_LOCAL_ORI", nullable = false, table = "TBIL_AVERBACAO")
private Localidade origem;
#ManyToOne(optional = false)
#JoinColumn(name = "CTL_LOCAL_DES", nullable = false, table = "TBIL_AVERBACAO")
private Localidade destino;
#ManyToOne(optional = true)
#JoinColumn(name = "CTL_LOCAL_FIM", nullable = true, table = "TBIL_AVERBACAO")
private Localidade destinoFinal;
#Column(name = "DHR_EMBAR", nullable = false, table = "TBIL_AVERBACAO")
#Temporal(TemporalType.DATE)
private Date dataEmbarque;
#Column(name = "IDT_CARGA_DSC", nullable = false, table = "TBIL_AVERBACAO")
private char tipoCargaDescarga;
#Column(name = "IDT_VEICU", nullable = false, table = "TBIL_AVERBACAO")
private String tipoVeiculo;
#Column(name = "STA_AVARI", nullable = false, table = "TBIL_AVERBACAO")
private char indicadorAvaria;
#Column(name = "STA_FLUVI", nullable = false, table = "TBIL_AVERBACAO")
private char indicadorTrechoFluvial;
#Column(name = "NUM_ETAPA_AVB", nullable = false, table = "TBIL_AVERBACAO")
#Type(type = "br.com.company.bilhetagem.brms.dao.jpa.types.EtapaAverbacaoUserType")
private EtapaAverbacao etapa;
public Averbacao() {
}
public Averbacao(final Proposta proposta) {
this.proposta = proposta;
}
#Transient
public AverbacaoPropostaKey getAverbacaoPropostaKey() {
final long numeroProposta =
this.proposta == null ? 0 : this.proposta.getNumeroProposta();
return new AverbacaoPropostaKey(this.numeroAverbacao, numeroProposta);
}
public Date getDataEmbarque() {
return new DateTime(dataEmbarque).toDate();
}
public Localidade getDestino() {
return destino;
}
public long getNumeroAverbacao() {
return numeroAverbacao;
}
public Localidade getOrigem() {
return origem;
}
public Proposta getProposta() {
return proposta;
}
public Double getValorIS() {
return valorIS;
}
public char getTipoCargaDescarga() {
return tipoCargaDescarga;
}
public String getTipoVeiculo() {
return tipoVeiculo;
}
public char getIndicadorAvaria() {
return indicadorAvaria;
}
public char getIndicadorTrechoFluvial() {
return indicadorTrechoFluvial;
}
public Localidade getDestinoFinal() {
return destinoFinal;
}
public final EtapaAverbacao getEtapa() {
return etapa;
}
public final void setEtapa(EtapaAverbacao etapa) {
this.etapa = etapa;
}
#Override
public String toString() {
return toStringHelper(this).addValue(this.numeroAverbacao)
.add("Proposta", this.proposta).add("Origem", this.origem)
.add("Destino", this.destino).addValue(this.dataEmbarque)
.addValue(this.valorIS).toString();
}
#Override
public int hashCode() {
return Objects.hashCode(this.dataEmbarque, this.destino,
this.numeroAverbacao, this.origem, this.proposta, this.valorIS,
this.tipoCargaDescarga, this.indicadorAvaria,
this.indicadorTrechoFluvial, this.destinoFinal);
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
final Averbacao that = (Averbacao) obj;
return equal(this.numeroAverbacao, that.getNumeroAverbacao())
&& equal(this.destino, that.getDestino())
&& equal(this.origem, that.getOrigem())
&& equal(this.proposta, that.getProposta());
}
}
EtapaAverbacao
public enum EtapaAverbacao implements Serializable, PersistentEnum {
NAO_PROCESSADO(1),
PROCESSANDO(2),
PROCESSADO(3);
private int id;
private EtapaAverbacao(final int id) {
this.id = id;
}
#Override
public int getId() {
return this.id;
}
}
public abstract class AbstractPersistentEnumUserType implements UserType {
public AbstractPersistentEnumUserType() {
}
public static List<Integer> toIdList(final List<? extends PersistentEnum> enumList) {
final List<Integer> ids = new ArrayList<Integer>();
if(enumList == null) {
return ids;
}
for(PersistentEnum e : enumList) {
ids.add(e.getId());
}
return ids;
}
public static List<Integer> toIdList(final PersistentEnum[] enumList) {
return toIdList(Arrays.asList(enumList));
}
#Override
public final int[] sqlTypes() {
return new int[] { Types.INTEGER };
}
#Override
public abstract Class<T> returnedClass();
#Override
public final boolean equals(Object obj1, Object obj2) {
if(obj1 == null) {
return false;
}
return obj1.equals(obj2);
}
#Override
public final int hashCode(Object obj) {
return obj == null ? 0 : obj.hashCode();
}
#Override
public final Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
if (rs.wasNull()) {
return null;
}
for (PersistentEnum value : returnedClass().getEnumConstants()) {
final int id = rs.getInt(names[0]);
if (id == value.getId()) {
return value;
}
}
throw new IllegalStateException("Unknown " + returnedClass().getSimpleName() + " id");
}
#Override
public final void nullSafeSet(PreparedStatement stmt, Object value, int index, SessionImplementor session) throws SQLException {
if (value == null) {
stmt.setNull(index, Types.INTEGER);
} else {
stmt.setInt(index, ((PersistentEnum) value).getId());
}
}
#Override
public final Object deepCopy(Object value) {
return value;
}
#Override
public final boolean isMutable() {
return false;
}
#Override
public final Serializable disassemble(Object value) {
return (Serializable) value;
}
#Override
public final Object assemble(Serializable cached, Object owner) {
return cached;
}
#Override
public final Object replace(Object original, Object target, Object owner) {
return original;
}
}
public class EtapaAverbacaoUserType extends
AbstractPersistentEnumUserType<EtapaAverbacao> {
#Override
public Class<EtapaAverbacao> returnedClass() {
return EtapaAverbacao.class;
}
}
After much effort I discovered with my team that the objects returned from query they were fetched as read only.
So, we get out the hint READ_ONLY in the query and now the objects can be updated

How to set and get values for Composite primary keys and other fields in jpa?

This is my Entity class
#EmbeddedId
private AuthorWorkPKEmbedded embeddedId;
#Column(name = "ColumnA")
private String ColumnA;
public AuthorWorkPKEmbedded getEmbeddedId() {
return embeddedId;
}
public void setEmbeddedId(AuthorWorkPKEmbedded embeddedId) {
this.embeddedId = embeddedId;
}
public String getColumnA() {
return ColumnA;
}
public void setColumnA(String ColumnA) {
this.ColumnA = ColumnA;
}
public AuthorWorkEmbedded() {
}
public AuthorWorkEmbedded(BigInteger bookId,BigInteger authorId) {
this.embeddedId = new AuthorWorkPKEmbedded(bookId, authorId);
}
This is my Embeddable class
#Embeddable
#Column(name = "bookId", nullable = false)
private BigInteger bookId;
#Column(name = "authorId", nullable = false)
private BigInteger authorId;
public AuthorWorkPKEmbedded() {
}
public AuthorWorkPKEmbedded(BigInteger bookId, BigInteger authorId) {
this.bookId = bookId;
this.authorId = authorId;
}
public BigInteger getBookId() {
return bookId;
}
public void setBookId(BigInteger bookId) {
this.bookId = bookId;
}
public BigInteger getAuthorId() {
return authorId;
}
public void setAuthorId(BigInteger authorId) {
this.authorId = authorId;
}
#Override
public int hashCode() {
return bookId.hashCode() + authorId.hashCode();
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof AuthorWorkPKEmbedded)) {
return false;
}
if (obj == null) {
return false;
}
AuthorWorkEmbedded pk=(AuthorWorkEmbedded) obj;
return (((bookId==((AuthorWorkPKEmbedded)obj).getBookId()))
&&((authorId==((AuthorWorkPKEmbedded)obj).getAuthorId())));
}
This is my main class
how set the composite values and why cant we use generatedvalue for autoincrement purpose and how to retrieve the values from the the database and one more thing where to declare other fields in Entity class or embeddable class and if not how to set and get the values from these 2 classes(entity and embeddable)
EntityTransaction entr = em.getTransaction();
entr.begin();
AuthorWorkPKEmbedded author = new AuthorWorkPKEmbedded();
author.setBookId(BigInteger.ONE);
author.setAuthorId(BigInteger.ONE);
AuthorWorkEmbedded a1=new AuthorWorkEmbedded();
a1.setEmbeddedId(author);
a1.setColumnA("Pirates of carrabian");
boolean successful = false;
try {
em.persist(author);
successful = true;
} finally {
if (successful) {
entr.commit();
} else {
entr.rollback();
}
}
Query query = em.createNamedQuery("AuthorWork.findAll");
List authorList = query.getResultList();
Iterator authorIterator = authorList.iterator();
while (authorIterator.hasNext()) {
author = (AuthorWorkPKEmbedded) authorIterator.next();
System.out.println("Book Id " + author.getBookId() + " " + "Author" + author.getAuthorId() + "");
System.out.println();
}
Use getters and setters for embeddedId .
Query query = em.createNamedQuery("AuthorWork.findAll");
List authorList = query.getResultList();
Iterator authorIterator = authorList.iterator();
while (authorIterator.hasNext()) {
author = (AuthorWorkEmbedded) authorIterator.next();
System.out.println("Book Id " + author.setEmbeddedId().getBookId() + " " + "Author" + author.getEmbeddedId().getAuthorId() + "");
System.out.println(""+author.getColumnA());
}

Categories