I've been having issues with the Where annotation
I have two tables on MySQL 8.0.18, Venues and Concerts, with this structure and fields
CREATE TABLE VENUE
(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(220) NOT NULL,
IMAGE VARCHAR(240),
ACTIVE BIT NOT NULL DEFAULT 0,
COORDINATES VARCHAR(120),
COUNTRY VARCHAR(120) NOT NULL DEFAULT 'USA',
CITY VARCHAR(220) NOT NULL DEFAULT 'None',
RATING INT NOT NULL DEFAULT 0,
VERSION INT NOT NULL DEFAULT 0,
PRIMARY KEY (ID)
);
CREATE TABLE CONCERT
(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(120) NOT NULL,
DESCRIPTION VARCHAR(120) NOT NULL,
FESTIVAL_ID INT,
VENUE_ID INT,
RATING INT NOT NULL DEFAULT 0,
DATE DATETIME,
IMAGE BLOB,
VERSION INT NOT NULL DEFAULT 0,
FOREIGN KEY (FESTIVAL_ID) REFERENCES FESTIVAL (ID),
FOREIGN KEY (VENUE_ID) REFERENCES VENUE (ID),
PRIMARY KEY (ID)
);
The Java Hibernate and Spring Data JPA configuration is as following
package com.heatmanofurioso.gigger.service.persistencehibernateimplementation.config;
import com.heatmanofurioso.gigger.service.persistencehibernateimplementation.HibernateServiceMarker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableJpaRepositories(basePackageClasses = {HibernateServiceMarker.class})
#ComponentScan(basePackageClasses = {HibernateServiceMarker.class})
#Slf4j
#EnableTransactionManagement
public class HibernateUtilConfig {
private static final String MYSQL_DATA_SOURCE = "java:jboss/MysqlDataSource";
private static final String HIBERNATE_ENTITIES = "com.heatmanofurioso.gigger.service.persistencehibernateimplementation.entity";
#Bean
public DataSource dataSource() {
JndiDataSourceLookup jndiDataSourceLookup = new JndiDataSourceLookup();
return jndiDataSourceLookup.getDataSource(MYSQL_DATA_SOURCE);
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan(HIBERNATE_ENTITIES);
log.info("Created entity manager successfully");
JpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
//Properties to show SQL format of tables on deploy
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.show_sql", true); // Mark as true to log hibernate queries
jpaProperties.put("hibernate.format_sql", true); // Mark as true to log hibernate queries
entityManagerFactoryBean.setJpaProperties(jpaProperties);
entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
return entityManagerFactoryBean;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
package com.heatmanofurioso.gigger.service.persistencehibernateimplementation.dao;
import com.heatmanofurioso.gigger.service.persistencehibernateimplementation.entity.VenueEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface VenueHibernateServiceImpl extends JpaRepository<VenueEntity, Long> {
#Query("SELECT t FROM VenueEntity t WHERE t.name like ?1")
List<VenueEntity> getByName(String name);
#Query("SELECT t FROM VenueEntity t WHERE t.coordinates = ?1")
List<VenueEntity> getByCoordinates(String coordinates);
}
package com.heatmanofurioso.gigger.service.persistencehibernateimplementation.dao;
import com.heatmanofurioso.gigger.service.persistencehibernateimplementation.entity.ConcertEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface ConcertHibernateServiceImpl extends JpaRepository<ConcertEntity, Long> {
#Query("SELECT t FROM ConcertEntity t WHERE t.name like ?1")
List<ConcertEntity> getByName(String name);
}
And I am successfully obtaining the following entities using Java 11 Spring JPA 5.2.0.RELEASE and Hibernate 5.4.8 deployed on a Wildfly 18.0.0.Final using the following entities
package com.heatmanofurioso.gigger.service.persistencehibernateimplementation.entity;
import org.hibernate.annotations.Where;
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 javax.persistence.Version;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "VENUE")
public class VenueEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", nullable = false)
private Long id;
#Column(name = "NAME", nullable = false)
private String name;
#Column(name = "IMAGE", nullable = false)
private String image;
#Column(name = "ACTIVE", nullable = false)
private Boolean active;
#Column(name = "COORDINATES")
private String coordinates;
#Column(name = "RATING")
private Long rating;
#Column(name = "COUNTRY")
private String country;
#Column(name = "CITY")
private String city;
#OneToMany(mappedBy = "venue", fetch = FetchType.EAGER)
private Set<ConcertEntity> concerts = new HashSet<>();
#Column(name = "VERSION")
#Version
private Long version;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getImage() {
return this.image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getCoordinates() {
return coordinates;
}
public void setCoordinates(String coordinates) {
this.coordinates = coordinates;
}
public Long getRating() {
return rating;
}
public void setRating(Long rating) {
this.rating = rating;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Set<ConcertEntity> getConcerts() {
return concerts;
}
public void setConcerts(Set<ConcertEntity> concerts) {
this.concerts = concerts;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}
package com.heatmanofurioso.gigger.service.persistencehibernateimplementation.entity;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "CONCERT")
public class ConcertEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", nullable = false)
private Long id;
#Column(name = "NAME", nullable = false)
private String name;
#Column(name = "DESCRIPTION")
private String description;
#Column(name = "RATING")
private Long rating;
#Column(name = "DATE", nullable = false)
private String date;
#Column(name = "IMAGE")
private String image;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name = "USER_CONCERT",
joinColumns = {#JoinColumn(name = "CONCERT_ID")},
inverseJoinColumns = {#JoinColumn(name = "USER_ID")}
)
private Set<UserEntity> userConcert = new HashSet<>();
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name = "CONCERT_ARTIST",
joinColumns = {#JoinColumn(name = "CONCERT_ID")},
inverseJoinColumns = {#JoinColumn(name = "ARTIST_ID")}
)
private Set<ArtistEntity> concertArtist = new HashSet<>();
#OneToOne
#JoinColumn(name = "FESTIVAL_ID", nullable = false)
private FestivalEntity festival;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "VENUE_ID")
private VenueEntity venue;
#Column(name = "VERSION")
#Version
private Long version;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getRating() {
return rating;
}
public void setRating(Long rating) {
this.rating = rating;
}
public LocalDateTime getDate() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(date, formatter);
}
public void setDate(LocalDateTime date) {
this.date = date.toString();
}
public String getDateString() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Set<UserEntity> getUserConcert() {
return userConcert;
}
public void setUserConcert(Set<UserEntity> userConcert) {
this.userConcert = userConcert;
}
public Set<ArtistEntity> getConcertArtist() {
return concertArtist;
}
public void setConcertArtist(Set<ArtistEntity> concertArtist) {
this.concertArtist = concertArtist;
}
public FestivalEntity getFestival() {
return festival;
}
public void setFestival(FestivalEntity festival) {
this.festival = festival;
}
public VenueEntity getVenue() {
return venue;
}
public void setVenue(VenueEntity venue) {
this.venue = venue;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}
The returned dataset corresponds to the following
Now, my issue is that if I try to add the #Where annotation to my Concerts collection on my VenueEntity, like so
#OneToMany(mappedBy = "venue", fetch = FetchType.EAGER)
private Set<ConcertEntity> concerts = new HashSet<>();
#OneToMany(mappedBy = "venue", fetch = FetchType.EAGER)
#Where(clause = "date < current_date")
private Set<ConcertEntity> pastConcerts = new HashSet<>();
#OneToMany(mappedBy = "venue", fetch = FetchType.EAGER)
#Where(clause = "date => current_date")
private Set<ConcertEntity> futureConcerts = new HashSet<>();
those two collections return empty datasets, even though, at the creation of the rows on the database, I am setting the value of the DATE field as current_date, so the pastConcerts collection should show results at least
Borh Sets are empty probably because current_date is null. Both predicates resolve to false in that case. It happens because hibernate cannot resolve a column named current_date and sets it to null.
You might work it around by using subselect, because clause is simply an sql predicate that gets pasted inside where on query creation (it depends on the database you're using):
#Where(clause = "date < (select * from current_date())")
Or shorter in some databases:
#Where(clause = "date < (select current_date())")
P.S.: In my opinion, this is not a good design. It's harder to test and makes every query concerning those sets unpredictible (same query can result in different results depending on time run).
I have the same association (literally the same FK column) mapped multiple times - but because Hibernate knows this is the same FK it considers them as the same.
Found out while debugging the SQL that Hibernate generated.
Essentially, this is not possible on the entity
Related
I have 2 tables that are bind in a "One to many" connection when I set the relation to EAGER , then the records are fetched from table A and then for each record the data is fetched from table B if let’s say I have 100 record in table B then 100 select query are done which is really bad for the performance. what do I need to do to the set it correct so all the data will be fetched in 1 query?
here is all the code: for table A (survey)
package hibernateDataFiles;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
/**
* Surveys generated by hbm2java
*/
#Entity
#Table(name = "surveys", schema = "edi_ms")
public class Survey implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long surveyId;
private String umn;
private String firstName;
private String middleName;
private String lastName;
private String phoneNumber;
private Date creationDate;
private Long shortFeedbackGrade;
private String shortFeedbackComment;
private List<MemberAnswer> memberAnswers = new ArrayList<MemberAnswer>(0);
private List<CategoryAnswer> categoriesAnswers = new ArrayList<CategoryAnswer>(0);
public Survey() {
}
public Survey(long surveyId, String firstName, String lastName, String phoneNumber, Date creationDate) {
this.surveyId = surveyId;
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.creationDate = creationDate;
}
public Survey(long surveyId, String umn, String firstName, String middleName, String lastName, String phoneNumber,
Date creationDate, Long shortFeedbackGrade, String shortFeedbackComment,
List<MemberAnswer> memberAnswers, List<CategoryAnswer> categoriesAnswer) {
this.surveyId = surveyId;
this.umn = umn;
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.creationDate = creationDate;
this.shortFeedbackGrade = shortFeedbackGrade;
this.shortFeedbackComment = shortFeedbackComment;
this.memberAnswers = memberAnswers;
this.categoriesAnswers = categoriesAnswer;
}
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "survey_id_seq")
#SequenceGenerator(allocationSize = 1, name = "survey_id_seq", sequenceName = "EDI_MS.survey_id_seq")
#Id
#Column(name = "survey_id", unique = true, nullable = false)
public long getSurveyId() {
return this.surveyId;
}
public void setSurveyId(long surveyId) {
this.surveyId = surveyId;
}
#Column(name = "umn", length = 15)
public String getUmn() {
return this.umn;
}
public void setUmn(String umn) {
this.umn = umn;
}
#Column(name = "first_name", nullable = false, length = 20)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "middle_name", length = 20)
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
#Column(name = "last_name", nullable = false, length = 20)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "phone_number", nullable = false, length = 15)
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "creation_date", nullable = false, length = 29)
public Date getCreationDate() {
return this.creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
#Column(name = "short_feedback_grade")
public Long getShortFeedbackGrade() {
return this.shortFeedbackGrade;
}
public void setShortFeedbackGrade(Long shortFeedbackGrade) {
this.shortFeedbackGrade = shortFeedbackGrade;
}
#Column(name = "short_feedback_comment", length = 500)
public String getShortFeedbackComment() {
return this.shortFeedbackComment;
}
public void setShortFeedbackComment(String shortFeedbackComment) {
this.shortFeedbackComment = shortFeedbackComment;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "survey")
#NotFound(action = NotFoundAction.IGNORE)
public List<MemberAnswer> getMemberAnswers() {
return this.memberAnswers;
}
public void setMemberAnswers(List<MemberAnswer> membersAnswers) {
this.memberAnswers = membersAnswers;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "survey")
#NotFound(action = NotFoundAction.IGNORE)
public List<CategoryAnswer> getCategoriesAnswers() {
return this.categoriesAnswers;
}
public void setCategoriesAnswers(List<CategoryAnswer> categoriesAnswers) {
this.categoriesAnswers = categoriesAnswers;
}
}
here is the JPA
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import hibernateDataFiles.Survey;
public interface SurveyRepository extends JpaRepository<Survey, Long> {
#Query("from Survey where ?1 <= creation_date and creation_date < ?2 ")
List<Survey> getSurveysByDates(Date fromDate , Date toDate );
}
here is table B (category_answers)
package hibernateDataFiles;
// Generated Jul 5, 2018 8:37:29 AM by Hibernate Tools 5.2.10.Final
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* CategoriesAnswers generated by hbm2java
*/
#Entity
#Table(name = "categories_answers", schema = "edi_ms")
public class CategoryAnswer implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private CategoryAnswerId id;
private Category category;
private Survey survey;
private long grade;
private String comment;
public CategoryAnswer() {
}
public CategoryAnswer(CategoryAnswerId id, Category category, Survey survey, long grade) {
this.id = id;
this.category = category;
this.survey = survey;
this.grade = grade;
}
public CategoryAnswer(CategoryAnswerId id, Category category, Survey survey, long grade, String comment) {
this.id = id;
this.category = category;
this.survey = survey;
this.grade = grade;
this.comment = comment;
}
#EmbeddedId
#AttributeOverrides({ #AttributeOverride(name = "surveyId", column = #Column(name = "survey_id", nullable = false)),
#AttributeOverride(name = "categoryId", column = #Column(name = "category_id", nullable = false)) })
public CategoryAnswerId getId() {
return this.id;
}
public void setId(CategoryAnswerId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "category_id", nullable = false, insertable = false, updatable = false)
public Category getCategory() {
return this.category;
}
public void setCategory(Category category) {
this.category = category;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "survey_id", nullable = false, insertable = false, updatable = false)
#JsonIgnore
public Survey getSurvey() {
return this.survey;
}
public void setSurvey(Survey survey) {
this.survey = survey;
}
#Column(name = "grade", nullable = false)
public long getGrade() {
return this.grade;
}
public void setGrade(long grade) {
this.grade = grade;
}
#Column(name = "comment", length = 500)
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
and categoryAnswerId (pk of the table )
package hibernateDataFiles;
// Generated Jul 5, 2018 8:37:29 AM by Hibernate Tools 5.2.10.Final
import javax.persistence.Column;
import javax.persistence.Embeddable;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
/**
* CategoriesAnswersId generated by hbm2java
*/
#Embeddable
public class CategoryAnswerId implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long surveyId;
private long categoryId;
public CategoryAnswerId() {
}
public CategoryAnswerId(long surveyId, long categoryId) {
this.surveyId = surveyId;
this.categoryId = categoryId;
}
#Column(name = "survey_id", nullable = false)
public long getSurveyId() {
return this.surveyId;
}
public void setSurveyId(long surveyId) {
this.surveyId = surveyId;
}
#Column(name = "category_id", nullable = false)
public long getCategoryId() {
return this.categoryId;
}
public void setCategoryId(long categoryId) {
this.categoryId = categoryId;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof CategoryAnswerId))
return false;
CategoryAnswerId castOther = (CategoryAnswerId) other;
return (this.getSurveyId() == castOther.getSurveyId()) && (this.getCategoryId() == castOther.getCategoryId());
}
public int hashCode() {
int result = 17;
result = 37 * result + (int) this.getSurveyId();
result = 37 * result + (int) this.getCategoryId();
return result;
}
}
and the JPA:
package repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import hibernateDataFiles.Category;
public interface CategoryRepository extends JpaRepository<Category, Long>{
#Transactional
#Modifying
#Query("update Category set expiration_date = current_date() where category_id = ?1 ")
void expireCategory(Long id );
#Query("from Category where function ('coalesce' ,effectiveDate ,current_date() ) <= current_date() "
+ "and function('coalesce' ,expirationDate , to_date('50001231','yyyymmdd')) > current_date() ")
List<Category> getEffective( );
}
You have the so called 1+n problem.
One solution is to tweak the fetch settings of the collection.
Can't find a JPA way on the short hand. But since your using Hibernate, this should work:
#org.hibernate.annotations.Fetch(FetchMode.JOIN) or better FetchMode.SUBSELECT
If you're executing a query, you have to adjust the query by adding join fetch.
I have read so much topics and still I cant solve my problem.
Problem: error from title. I get it every time I try to read entity from database.
Database is mysql one, connected by jdbc driver.
Here is my code: First one is ReadStudentDemo (to read from database)
package entities;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.EntityTransaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class ReadStudentDemo {
public static void main(String[] args) throws ParseException {
Player roggy = new Player();
Configuration conf = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Player.class);
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
EntityTransaction tx = session.beginTransaction();
roggy = (Player)session.get(Player.class, 4);
tx.commit();
System.out.println(roggy);
}
}
second is Player.java with Player entity mapped.
package entities;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Player generated by hbm2java
*/
#Entity
#Table(name = "Player", catalog = "sql11217012")
public class Player implements java.io.Serializable {
private Integer id;
private String firstName;
private String lastName;
private Date birth;
private Float wl;
private Integer win;
private BigDecimal money;
private Set<Match> matchesForPlayerId = new HashSet<Match>(0);
private Set<Match> matchesForPlayer1Id = new HashSet<Match>(0);
private Set<Match> matchesForCourtId = new HashSet<Match>(0);
public Player() {
}
public Player(String firstName, String lastName, Date birth, Float wl, Integer win, BigDecimal money,
Set<Match> matchesForPlayerId, Set<Match> matchesForPlayer1Id, Set<Match> matchesForCourtId) {
this.firstName = firstName;
this.lastName = lastName;
this.birth = birth;
this.wl = wl;
this.win = win;
this.money = money;
this.matchesForPlayerId = matchesForPlayerId;
this.matchesForPlayer1Id = matchesForPlayer1Id;
this.matchesForCourtId = matchesForCourtId;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "first_name", length = 45)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "last_name", length = 45)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Temporal(TemporalType.DATE)
#Column(name = "birth", length = 10)
public Date getBirth() {
return this.birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
#Column(name = "wl", precision = 12, scale = 0)
public Float getWl() {
return this.wl;
}
public void setWl(Float wl) {
this.wl = wl;
}
#Column(name = "win")
public Integer getWin() {
return this.win;
}
public void setWin(Integer win) {
this.win = win;
}
#Column(name = "money", precision = 15)
public BigDecimal getMoney() {
return this.money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "playerByPlayerId")
public Set<Match> getMatchesForPlayerId() {
return this.matchesForPlayerId;
}
public void setMatchesForPlayerId(Set<Match> matchesForPlayerId) {
this.matchesForPlayerId = matchesForPlayerId;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "playerByPlayer1Id")
public Set<Match> getMatchesForPlayer1Id() {
return this.matchesForPlayer1Id;
}
public void setMatchesForPlayer1Id(Set<Match> matchesForPlayer1Id) {
this.matchesForPlayer1Id = matchesForPlayer1Id;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "playerByCourtId")
public Set<Match> getMatchesForCourtId() {
return this.matchesForCourtId;
}
public void setMatchesForCourtId(Set<Match> matchesForCourtId) {
this.matchesForCourtId = matchesForCourtId;
}
}
Then you have Match entity.
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "Match", catalog = "sql11217012")
public class Match implements java.io.Serializable {
private Integer id;
private Player playerByPlayerId;
private Player playerByPlayer1Id;
private Player playerByCourtId;
public Match() {
}
public Match(Player playerByPlayerId, Player playerByPlayer1Id, Player playerByCourtId) {
this.playerByPlayerId = playerByPlayerId;
this.playerByPlayer1Id = playerByPlayer1Id;
this.playerByCourtId = playerByCourtId;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "player_id", nullable = false)
public Player getPlayerByPlayerId() {
return this.playerByPlayerId;
}
public void setPlayerByPlayerId(Player playerByPlayerId) {
this.playerByPlayerId = playerByPlayerId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "player1_id", nullable = false)
public Player getPlayerByPlayer1Id() {
return this.playerByPlayer1Id;
}
public void setPlayerByPlayer1Id(Player playerByPlayer1Id) {
this.playerByPlayer1Id = playerByPlayer1Id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "court_id", nullable = false)
public Player getPlayerByCourtId() {
return this.playerByCourtId;
}
public void setPlayerByCourtId(Player playerByCourtId) {
this.playerByCourtId = playerByCourtId;
}
}
And then the stack trace
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Exception in thread "main" org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: entities.Player.matchesForCourtId[entities.Match]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1253)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:810)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:735)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:54)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1621)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1589)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at entities.ReadStudentDemo.main(ReadStudentDemo.java:50)
Thanks in advance for any help!
Well you add Player to your Configuration
Configuration conf = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Player.class);
but seems you never add Match.class?
So probably you should use
Configuration conf = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Player.class)
.addAnnotatedClass(Match.class);
I am generating my Annotated Code Classes with hibernate and eclipse JBoss plugin, For the One to Many & Many to Many Relationships etc, the code generated used Set type for collections and generate many to many as one to many relation.
Project:
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Project generated by hbm2java
*/
#Entity
#Table(name = "project", schema = "public")
public class Project implements java.io.Serializable
{
private int projectId;
private Type type;
private Customer customer;
private String projectName;
private String description;
private Double totalContractAmount;
private Set projectConstructionMaterials = new HashSet( 0 );
public Project()
{
}
public Project(int projectId)
{
this.projectId = projectId;
}
public Project(int projectId, Type type, Customer customer, String projectName, String description,
Double totalContractAmount,
Set projectConstructionMaterials)
{
this.projectId = projectId;
this.type = type;
this.customer = customer;
this.projectName = projectName;
this.description = description;
this.totalContractAmount = totalContractAmount;
this.projectConstructionMaterials = projectConstructionMaterials;
}
#Id
#Column(name = "project_id", unique = true, nullable = false)
public int getProjectId()
{
return this.projectId;
}
public void setProjectId(int projectId)
{
this.projectId = projectId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "type_id")
public Type getType()
{
return this.type;
}
public void setType(Type type)
{
this.type = type;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "customer_id")
public Customer getCustomer()
{
return this.customer;
}
public void setCustomer(Customer customer)
{
this.customer = customer;
}
#Column(name = "project_name")
public String getProjectName()
{
return this.projectName;
}
public void setProjectName(String projectName)
{
this.projectName = projectName;
}
#Column(name = "description", length = 500)
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project") //it should be many to many annotation
public Set getProjectConstructionMaterials()
{
return this.projectConstructionMaterials;
}
public void setProjectConstructionMaterials(Set projectConstructionMaterials)
{
this.projectConstructionMaterials = projectConstructionMaterials;
}
}
ProjectConstructionMaterial
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* ProjectConstructionMaterial generated by hbm2java
*/
#Entity
#Table(name = "project_construction_material", schema = "public")
public class ProjectConstructionMaterial implements java.io.Serializable
{
private int projectConstructionMaterialId;
private ConstructionMaterialInventory constructionMaterialInventory;
private Project project;
private String description;
private String quantityArrived;
private String quantityConsumed;
public ProjectConstructionMaterial()
{
}
public ProjectConstructionMaterial(int projectConstructionMaterialId)
{
this.projectConstructionMaterialId = projectConstructionMaterialId;
}
public ProjectConstructionMaterial(int projectConstructionMaterialId,
ConstructionMaterialInventory constructionMaterialInventory, Project project, String description,
String quantityArrived, String quantityConsumed)
{
this.projectConstructionMaterialId = projectConstructionMaterialId;
this.constructionMaterialInventory = constructionMaterialInventory;
this.project = project;
this.description = description;
this.quantityArrived = quantityArrived;
this.quantityConsumed = quantityConsumed;
}
#Id
#Column(name = "project_construction_material_id", unique = true, nullable = false)
public int getProjectConstructionMaterialId()
{
return this.projectConstructionMaterialId;
}
public void setProjectConstructionMaterialId(int projectConstructionMaterialId)
{
this.projectConstructionMaterialId = projectConstructionMaterialId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "construction_material_id")
public ConstructionMaterialInventory getConstructionMaterialInventory()
{
return this.constructionMaterialInventory;
}
public void setConstructionMaterialInventory(ConstructionMaterialInventory constructionMaterialInventory)
{
this.constructionMaterialInventory = constructionMaterialInventory;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "project_id")
public Project getProject()
{
return this.project;
}
public void setProject(Project project)
{
this.project = project;
}
#Column(name = "description", length = 500)
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
#Column(name = "quantity_arrived")
public String getQuantityArrived()
{
return this.quantityArrived;
}
public void setQuantityArrived(String quantityArrived)
{
this.quantityArrived = quantityArrived;
}
#Column(name = "quantity_consumed")
public String getQuantityConsumed()
{
return this.quantityConsumed;
}
public void setQuantityConsumed(String quantityConsumed)
{
this.quantityConsumed = quantityConsumed;
}
}
ConstructionMaterialInventory
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* ConstructionMaterialInventory generated by hbm2java
*/
#Entity
#Table(name = "construction_material_inventory", schema = "public")
public class ConstructionMaterialInventory implements java.io.Serializable
{
private int constructionMaterialId;
private Type type;
private SubType subType;
private String quantity;
private String description;
private Set projectConstructionMaterials = new HashSet( 0 );
public ConstructionMaterialInventory()
{
}
public ConstructionMaterialInventory(int constructionMaterialId)
{
this.constructionMaterialId = constructionMaterialId;
}
public ConstructionMaterialInventory(int constructionMaterialId, Type type, SubType subType, String quantity,
String description, Set projectConstructionMaterials)
{
this.constructionMaterialId = constructionMaterialId;
this.type = type;
this.subType = subType;
this.quantity = quantity;
this.description = description;
this.projectConstructionMaterials = projectConstructionMaterials;
}
#Id
#Column(name = "construction_material_id", unique = true, nullable = false)
public int getConstructionMaterialId()
{
return this.constructionMaterialId;
}
public void setConstructionMaterialId(int constructionMaterialId)
{
this.constructionMaterialId = constructionMaterialId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "type_id")
public Type getType()
{
return this.type;
}
public void setType(Type type)
{
this.type = type;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "sub_type_id")
public SubType getSubType()
{
return this.subType;
}
public void setSubType(SubType subType)
{
this.subType = subType;
}
#Column(name = "quantity")
public String getQuantity()
{
return this.quantity;
}
public void setQuantity(String quantity)
{
this.quantity = quantity;
}
#Column(name = "description", length = 500)
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "constructionMaterialInventory")
public Set getProjectConstructionMaterials()
{
return this.projectConstructionMaterials;
}
public void setProjectConstructionMaterials(Set projectConstructionMaterials)
{
this.projectConstructionMaterials = projectConstructionMaterials;
}
}
Data Model
I want to change it to many to many annotations and also want to use List or ArrayList instead of Set. Can anyone please tell me how to do this with automatically code generation? Beause i have dozens of table like this and change in tables manually takes too much time..
For Example: Annotation Must be generate automatically as described in this example.
Many to Many annotation Example
I have used many to one bidirectional relationship here I can't delete the files once i have been had into database if I am trying to delete I am getting exception has Cannot delete or update a parent row: a foreign key constraint fails.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.treamis.entity;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
/**
*
* #author
* admin
*/
#Entity
#Table(name = "LibraryBookListTable")
public class LibraryBookListEntity implements Serializable {
#Id
#GeneratedValue
#Column(name = "BookListId")
private int booklistid;
#Column(name = "ISBN", nullable = false)
private String isbn;
#Column(name = "edition", nullable = false)
private String edition;
#Column(name = "publisher", nullable = false)
private String publisher;
#Column(name = "place", nullable = false)
private String place;
#Column(name = "page", nullable = false)
private String page;
#Column(name = "source", nullable = false)
private String source;
#Column(name = "billno", nullable = false)
private String billno;
#Column(name = "callno", nullable = false)
private String callno;
#Column(name = "BookTitle", nullable = false)
private String booktitle;
#Column(name = "BookAuthor", nullable = false)
private String author;
#Column(name = "BookPrice", nullable = false)
private float price;
#Column(name = "RackNumber", nullable = false)
private String rack;
#Column(name = "PublishedYear", nullable = false)
private String publishedyear;
#Column(name = "NoofCopies", nullable = false)
private int tcopies;
#Column(name = "DateAdded", nullable = false)
private java.sql.Date dateAdded;
#Column(name = "billdate", nullable = false)
private java.sql.Date billdate;
#ManyToOne(fetch = FetchType.LAZY, targetEntity = CategoryEntity.class, cascade = CascadeType.ALL)
#JoinColumn(name = "category_Id", referencedColumnName = "category_Id", nullable = true)
private CategoryEntity categoryid;
#OneToOne
private UserEntity addedBy;
#OneToOne
private UserEntity modifiedBy;
#OneToMany(fetch = FetchType.LAZY, targetEntity = LibraryBarCodeEntity.class, cascade = CascadeType.ALL, mappedBy = "S_no")
#JoinColumn(name = "BookListId", referencedColumnName = "BookListId")
private Set< LibraryBarCodeEntity> chield;
public Set<LibraryBarCodeEntity> getChield() {
return chield;
}
public void setChield(Set<LibraryBarCodeEntity> chield) {
this.chield = chield;
}
//#Column(name = "AddedDate", nullable = false)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private java.util.Date addedate;
// #Column(name = "ModifiedDate", nullable = false)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private java.util.Date modifiedDate;
public int getBooklistid() {
return booklistid;
}
public void setBooklistid(int booklistid) {
this.booklistid = booklistid;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getBooktitle() {
return booktitle;
}
public void setBooktitle(String booktitle) {
this.booktitle = booktitle;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getRack() {
return rack;
}
public void setRack(String rack) {
this.rack = rack;
}
public int getTcopies() {
return tcopies;
}
public void setTcopies(int tcopies) {
this.tcopies = tcopies;
}
public java.sql.Date getDateAdded() {
return dateAdded;
}
public void setDateAdded(java.sql.Date dateAdded) {
this.dateAdded = dateAdded;
}
public CategoryEntity getCategoryid() {
return categoryid;
}
public void setCategoryid(CategoryEntity categoryid) {
this.categoryid = categoryid;
}
public UserEntity getAddedBy() {
return addedBy;
}
public void setAddedBy(UserEntity addedBy) {
this.addedBy = addedBy;
}
public UserEntity getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(UserEntity modifiedBy) {
this.modifiedBy = modifiedBy;
}
public java.util.Date getAddedate() {
return addedate;
}
public void setAddedate(java.util.Date addedate) {
this.addedate = addedate;
}
public java.util.Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(java.util.Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
// public String getAccessionnumber() {
// return accessionnumber;
// }
//
// public void setAccessionnumber(String accessionnumber) {
// this.accessionnumber = accessionnumber;
// }
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getBillno() {
return billno;
}
public void setBillno(String billno) {
this.billno = billno;
}
public String getCallno() {
return callno;
}
public void setCallno(String callno) {
this.callno = callno;
}
public java.sql.Date getBilldate() {
return billdate;
}
public void setBilldate(java.sql.Date billdate) {
this.billdate = billdate;
}
public String getPublishedyear() {
return publishedyear;
}
public void setPublishedyear(String publishedyear) {
this.publishedyear = publishedyear;
}
// public Set< LibraryBarCodeEntity> getChield() {
// return chield;
// }
//
// public void setChield(Set< LibraryBarCodeEntity> chield) {
// this.chield = chield;
// }
}
This is my another entity class..
package com.treamis.entity;
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.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* #author
* admin
*/
#Entity
#Table(name = "LibraryBarCodeTable")
public class LibraryBarCodeEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "S_no", nullable = false)
private int S_no;
#Column(name = "BookBarCode", nullable = false)
private String barCode;
private String accessno;
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = LibraryBookListEntity.class)
#JoinColumn(name = "BookListId", referencedColumnName = "BookListId")
private LibraryBookListEntity parent;
public LibraryBookListEntity getParent() {
return parent;
}
public void setParent(LibraryBookListEntity parent) {
this.parent = parent;
}
public int getS_no() {
return S_no;
}
public void setS_no(int S_no) {
this.S_no = S_no;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public String getAccessno() {
return accessno;
}
public void setAccessno(String accessno) {
this.accessno = accessno;
}
}
Hi this is my complete stack trace
2014-01-09 15:44:26 ERROR JDBCExceptionReporter:78 - Cannot delete or update a parent row: a foreign key constraint fails (`treamisdemo`.`librarybooklisttable`, CONSTRAINT `FK33BC700C2F4991AA` FOREIGN KEY (`category_Id`) REFERENCES `categoryentity` (`category_Id`))
2014-01-09 15:44:26 ERROR AbstractFlushingEventListener:301 - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:146)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.treamis.library.BookList.LibraryBookListDelete.execute(LibraryBookListDelete.java:90)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
I don't know of this will help, but if you haven't already done so, you can edit your hibernate.cfg.xml file and set hibernate.show_sql from false to true in order to see what sql statements are generated when the exception occurs. Examining them may provide you a clue on what is going on. You may also consider putting print statements (System.out.println) in your set*() functions to see what primary and foreign key values are so you can examine the data in the database (now that you know the primary key value, you can see what record is being processed).
Example: System.out.println("in MyDaoClass: calling customer table: setId()="+customer.getID());
As I referenced in the title I have two entities in google app engine project. The first one is "store" and the other is "product". Before adding the ManyToMany annotation the entities stored regularly but after the relationship addition the entities cannot be stored even though there is a successful message returned!!
Here are the entities:
Store.java
package com.cheapchase.server;
import java.util.Date;
import java.util.Set;
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.ManyToMany;
import javax.persistence.Table;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name="store", catalog="content", uniqueConstraints={
#UniqueConstraint(columnNames = "STORE_NAME"),
#UniqueConstraint(columnNames = "STORE_CODE")})
public class Store{
private int storeCode;
private Date dueDate;
private String emailAddress;
private String storeName;
private String storeAddress;
private String storeDescription;
private String userId;
private Long id;
private Set<Product> product;
public Store(){
}
public Store(String storeName, int storeCode){
this.storeName = storeName;
this.setStoreCode(storeCode);
}
public Store(String storeName, int storeCode, Set<Product> product){
this.storeName = storeName;
this.storeCode = storeCode;
this.product = product;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "STORE_ID", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="STORE_NAME", nullable=false)
public String getStoreName() {
return this.storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
/*
* Define the Many To Many relationship with product
*/
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "storae_product", catalog = "content", joinColumns = {
#JoinColumn(name = "STORE_ID", nullable = false)},
inverseJoinColumns = {#JoinColumn(name = "PRODUCT_ID", nullable = false)})
public Set<Product> getProduct(){
return this.product;
}
public void setProduct(Set<Product> product){
this.product = product;
}
/*
* Define the rest getters and setters
*/
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public String getEmailAddress() {
return this.emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getStoreDescription() {
return storeDescription;
}
public void setStoreDescription(String storeDescription) {
this.storeDescription = storeDescription;
}
public String getStoreAddress() {
return storeAddress;
}
public void setStoreAddress(String storeAddress) {
this.storeAddress = storeAddress;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public int getStoreCode() {
return storeCode;
}
public void setStoreCode(int storeCode) {
this.storeCode = storeCode;
}
public String toString(){
StringBuilder builder = new StringBuilder();
builder.append("Store [dueDate=");
builder.append(dueDate);
builder.append(", name=");
builder.append(storeName);
builder.append(", description=");
builder.append(storeDescription);
builder.append("]");
return builder.toString();
}
}
Product.java
package com.cheapchase.server;
import java.util.Set;
import java.util.HashSet;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Column;
import com.google.appengine.api.datastore.Blob;
#Entity
#Table(name = "product", catalog = "content")
public class Product {
private Long productId;
private String name;
private String description;
private int barCode;
Blob image;
private Set<Store> stores = new HashSet<Store>(0);
public Product(){
}
public Product(String name, String description){
this.name = name;
this.description = description;
}
public Product(String name, String description, Set<Store> stores){
this.name = name;
this.description = description;
this.stores = stores;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "PRODUCT_ID", unique = true, nullable = false)
public Long getProductId(){
return this.productId;
}
public void setProductId(Long productId){
this.productId = productId;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "product")
public Set<Store> getStore(){
return this.stores;
}
public void setStore(Set<Store> store){
this.stores = store;
}
public int getBarCode() {
return barCode;
}
public void setBarCode(int barCode) {
this.barCode = barCode;
}
}