I'm working with hibernate 4 and Maven :
package tn.onp.mvno.model;
#Entity
#Table(name="PERSON")
public class Person {
private int id;
private String name;
private String surname;
private String email;
private String adresse;
private String MobilePhone;
/**
* Get User Id
*
* #return int - User Id
*/
#Id
#GeneratedValue
#Column(name="ID")
public int getId() {
return id;
}
/**
* Set User Id
*
* #param int - User Id
*/
public void setId(int id) {
this.id = id;
}
}
package tn.onp.mvno.model;
#Entity
#Inheritance(strategy= InheritanceType.TABLE_PER_CLASS)
#Table(name="USER")
public class User extends Person{
private String SIMCardNumber;
private String SIMCardValidityDate;
private Collection<Call> calls;
private Collection<Credit> credits;
#Column(name="SIMCARDNUMBER", unique = true, nullable = false)
public String getSIMCardNumber() {
return SIMCardNumber;
}
public void setSIMCardNumber(String sIMCardNumber) {
SIMCardNumber = sIMCardNumber;
}
#Column(name="SIMCARDVALIDITYDATE", nullable = false)
public String getSIMCardValidityDate() {
return SIMCardValidityDate;
}
public void setSIMCardValidityDate(String sIMCardValidityDate) {
SIMCardValidityDate = sIMCardValidityDate;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
public Collection<Call> getCalls() {
return calls;
}
public void setCalls(Collection<Call> calls) {
this.calls = calls;
}
}
Call.java
#Entity
#Table(name="CALL")
public class Call {
private String callId;
private String telNumber;
private String term;
private String duration;
private String direction;
private User user;
/** Get the callId
* #return the callId
*/
#Id
#GeneratedValue
#Column(name="CALLID")
public String getCallId() {
return callId;
}
/** Set the callId
* #param callId the callId to set
*/
public void setCallId(String callId) {
this.callId = callId;
}
/** Get the telNumber
* #return the telNumber
*/
#Column(name="TELNUMBER")
public String getTelNumber() {
return telNumber;
}
/** Set the telNumber
* #param telNumber the telNumber to set
*/
public void setTelNumber(String telNumber) {
this.telNumber = telNumber;
}
/** Get the term
* #return the term
*/
#Column(name="TERM")
public String getTerm() {
return term;
}
/** Set the term
* #param term the term to set
*/
public void setTerm(String term) {
this.term = term;
}
/** Get the duration
* #return the duration
*/
#Column(name="DURATION")
public String getDuration() {
return duration;
}
/** Set the duration
* #param duration the duration to set
*/
public void setDuration(String duration) {
this.duration = duration;
}
/** Get the direction
* #return the direction
*/
#Column(name="DIRECTION")
public String getDirection() {
return direction;
}
/** Set the direction
* #param direction the direction to set
*/
public void setDirection(String direction) {
this.direction = direction;
}
/** Get the user
* #return the user
*/
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id")
public User getUser() {
return user;
}
/** Set the user
* #param user the user to set
*/
public void setUser(User user) {
this.user = user;
}
}
When i deploy the application on tomcat server and run it i get this error :
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: alter table CALL drop foreign key FK1F725EE04824FE
févr. 11, 2013 5:53:38 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table CALL drop foreign key FK1F725EE04824FE
févr. 11, 2013 5:53:38 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'CALL drop foreign key
FK1F725EE04824FE' at line 1
Hibernate: drop table if exists CALL
févr. 11, 2013 5:53:38 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: drop table if exists CALL
févr. 11, 2013 5:53:38 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'CALL' at line 1
Hibernate: drop table if exists CREDIT
Hibernate: drop table if exists PERSON
Hibernate: create table CALL (CALLID varchar(255) not null auto_increment, DIRECTION
varchar(255), DURATION varchar(255), TELNUMBER varchar(255), TERM varchar(255), id
integer, primary key (CALLID))
févr. 11, 2013 5:53:38 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: create table CALL (CALLID varchar(255) not null
auto_increment, DIRECTION varchar(255), DURATION varchar(255), TELNUMBER varchar(255),
TERM varchar(255), id integer, primary key (CALLID))
févr. 11, 2013 5:53:38 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'CALL (CALLID varchar(255) not
null auto_increment, DIRECTION varchar(255), DURAT' at line 1
CALL is a reserved word. Choose another table name.
Related
The entity classes are as given below
I am not sure if this is problem with how Hibernate or Spring Data understands my input. In my project on backend I am using Java + Spring Data + Hibernate + PostgreSQL.
I am able to get and delete data from the database but not add to it.
//AlbumEntity
``
#Entity
#Table(name = "albums")
public class AlbumEntity extends ApplicationPersistenceEntity implements Album {
#Id
#Column(name = "album_id")
// #GeneratedValue(strategy = GenerationType.IDENTITY)
private long albumId;
#Column(name = "NAME")
private String albumName;
#Column(name = "Genre")
private String genre;
#ManyToOne(cascade = CascadeType.PERSIST, optional = true, fetch = FetchType.LAZY)
#JoinColumn(name = "singer_id", nullable = false)
// #NotFound(action = NotFoundAction.IGNORE)
private SingerEntity singer;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "album")
private List<SongEntity> songs;
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public AlbumEntity() {
}
/**
* The constructor.
*
* #param albumId
* #param albumName
* #param genre
* #param singer
* #param songs
*/
public AlbumEntity(long albumId, String albumName, String genre, SingerEntity singer, List<SongEntity> songs) {
super();
this.albumId = albumId;
this.albumName = albumName;
this.genre = genre;
this.singer = singer;
this.songs = songs;
}
/**
* #return albumId
*/
#Override
public long getAlbumId() {
return this.albumId;
}
/**
* #param albumId new value of {#link #getalbumId}.
*/
#Override
public void setAlbumId(long albumId) {
this.albumId = albumId;
}
/**
* #return albumName
*/
#Override
public String getAlbumName() {
return this.albumName;
}
/**
* #param albumName new value of {#link #getalbumName}.
*/
#Override
public void setAlbumName(String albumName) {
this.albumName = albumName;
}
/**
* #return genre
*/
#Override
public String getGenre() {
return this.genre;
}
/**
* #param genre new value of {#link #getgenre}.
*/
#Override
public void setGenre(String genre) {
this.genre = genre;
}
/**
* #return singer
*/
public SingerEntity getSinger() {
return this.singer;
}
/**
* #param singer new value of {#link #getsinger}.
*/
public void setSinger(SingerEntity singer) {
this.singer = singer;
}
/**
* #return songs
*/
public List<SongEntity> getSongs() {
return this.songs;
}
/**
* #param songs new value of {#link #getsongs}.
*/
public void setSongs(List<SongEntity> songs) {
this.songs = songs;
}
#Override
#Transient
public Long getSingerId() {
if (this.singer == null) {
return null;
}
return this.singer.getId();
}
#Override
public void setSingerId(Long singerId) {
if (singerId == null) {
this.singer = null;
} else {
SingerEntity singerEntity = new SingerEntity();
singerEntity.setId(singerId);
this.singer = singerEntity;
}
}
}
//Song Entity
#Entity
#Table(name = "songs")
public class SongEntity extends ApplicationPersistenceEntity implements Song {
#Id
#Column(name = "song_id")
// #GeneratedValue(strategy = GenerationType.IDENTITY)
private long songId;
#Column(name = "Title")
private String title;
#Column(name = "Content")
private String content;
#ManyToOne(cascade = CascadeType.PERSIST, optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "singer_id", nullable = false)
private SingerEntity singer;
#ManyToOne(cascade = CascadeType.PERSIST, optional = true, fetch = FetchType.LAZY)
#JoinColumn(name = "album_id")
private AlbumEntity album;
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public SongEntity() {
}
/**
* The constructor.
*
* #param songId
* #param title
* #param content
* #param singer
* #param album
*/
public SongEntity(long songId, String title, String content, SingerEntity singer, AlbumEntity album) {
super();
this.songId = songId;
this.title = title;
this.content = content;
this.singer = singer;
this.album = album;
}
/**
* #return songId
*/
#Override
public long getSongId() {
return this.songId;
}
/**
* #param songId new value of {#link #getsongId}.
*/
#Override
public void setSongId(long songId) {
this.songId = songId;
}
/**
* #return title
*/
#Override
public String getTitle() {
return this.title;
}
/**
* #param title new value of {#link #gettitle}.
*/
#Override
public void setTitle(String title) {
this.title = title;
}
/**
* #return content
*/
#Override
public String getContent() {
return this.content;
}
/**
* #param content new value of {#link #getcontent}.
*/
#Override
public void setContent(String content) {
this.content = content;
}
/**
* #return singer
*/
public SingerEntity getSinger() {
return this.singer;
}
/**
* #param singer new value of {#link #getsinger}.
*/
public void setSinger(SingerEntity singer) {
this.singer = singer;
}
/**
* #return album
*/
public AlbumEntity getAlbum() {
return this.album;
}
/**
* #param album new value of {#link #getalbum}.
*/
public void setAlbum(AlbumEntity album) {
this.album = album;
}
#Override
#Transient
public Long getSingerId() {
if (this.singer == null) {
return null;
}
return this.singer.getId();
}
#Override
public void setSingerId(Long singerId) {
if (singerId == null) {
this.singer = null;
} else {
SingerEntity singerEntity = new SingerEntity();
singerEntity.setId(singerId);
this.singer = singerEntity;
}
}
#Override
#Transient
public Long getAlbumId() {
if (this.album == null) {
return null;
}
return this.album.getId();
}
#Override
public void setAlbumId(Long albumId) {
if (albumId == null) {
this.album = null;
} else {
AlbumEntity albumEntity = new AlbumEntity();
albumEntity.setId(albumId);
this.album = albumEntity;
}
}
}
singer entity
#Entity
#Table(name = "singers")
public class SingerEntity extends ApplicationPersistenceEntity implements Singer {
#Id
#Column(name = "singer_id")
// #GeneratedValue(strategy = GenerationType.IDENTITY)
private long singerId;
#Column(name = "First_NAME")
private String firstname;
#Column(name = "Last_NAME")
private String lastname;
#Column(name = "Gender")
private String gender;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "singer")
private List<SongEntity> songs;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "singer")
private List<AlbumEntity> albums;
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public SingerEntity() {
}
/**
* The constructor.
*
* #param singerId
* #param firstname
* #param lastname
* #param gender
* #param songs
* #param albums
*/
public SingerEntity(long singerId, String firstname, String lastname, String gender, List<SongEntity> songs,
List<AlbumEntity> albums) {
super();
this.singerId = singerId;
this.firstname = firstname;
this.lastname = lastname;
this.gender = gender;
this.songs = songs;
this.albums = albums;
}
/**
* #return singerId
*/
#Override
public long getSingerId() {
return this.singerId;
}
/**
* #param singerId new value of {#link #getsingerId}.
*/
#Override
public void setSingerId(long singerId) {
this.singerId = singerId;
}
/**
* #return firstname
*/
#Override
public String getFirstname() {
return this.firstname;
}
/**
* #param firstname new value of {#link #getfirstname}.
*/
#Override
public void setFirstname(String firstname) {
this.firstname = firstname;
}
/**
* #return lastname
*/
#Override
public String getLastname() {
return this.lastname;
}
/**
* #param lastname new value of {#link #getlastname}.
*/
#Override
public void setLastname(String lastname) {
this.lastname = lastname;
}
/**
* #return gender
*/
#Override
public String getGender() {
return this.gender;
}
/**
* #param gender new value of {#link #getgender}.
*/
#Override
public void setGender(String gender) {
this.gender = gender;
}
/**
* #return songs
*/
public List<SongEntity> getSongs() {
return this.songs;
}
/**
* #param songs new value of {#link #getsongs}.
*/
public void setSongs(List<SongEntity> songs) {
this.songs = songs;
}
/**
* #return albums
*/
public List<AlbumEntity> getAlbums() {
return this.albums;
}
/**
* #param albums new value of {#link #getalbums}.
*/
public void setAlbums(List<AlbumEntity> albums) {
this.albums = albums;
}
}
While checking Post endpoint
"modificationCounter": 2,
"id": 302,
"songId": 302,
"title": "As it was",
"content": "songs",
"singer_id": 201,
"album_id": 101
I am giving this data...still there is this error
org.postgresql.util.PSQLException: ERROR: null value in column "album_id" of relation "songs" violates not-null constraint
Detail: Failing row contains (302, 2, 302, As it was, songs, null, null).
This one keeps on coming... I guess you are using your entities as DTOs. DON'T
The problem is that you send an ID for albumID and singerID which are objects in Java.
For this to work, create a DTO that maps your fields and lookup the IDs in your database then create your Song Entity with those. Also, you need to map back the song in your album and singer for JPA to work correctly.
I do have an entity OptionGroup with relationships to other entities. One of the relationships is making trouble: An OptionGroup has an owner (User). When I delete an OptionGroup, for some reason, the JPA provider hibernate is trying to set the owner_id of the OptionGroup to null which violates to the NotNull constraint defined for the owner field. I have no clue why hibernate is doing this, but I can see that it is doing this in the log:
2022-08-30 20:17:53.008 DEBUG 17488 --- [nio-8081-exec-1] org.hibernate.SQL : update option_group set description=?, option_group_name=?, owner_id=? where id=?
2022-08-30 20:17:53.008 TRACE 17488 --- [nio-8081-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [null]
2022-08-30 20:17:53.008 TRACE 17488 --- [nio-8081-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [Männliche Vornamen]
2022-08-30 20:17:53.008 TRACE 17488 --- [nio-8081-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [BIGINT] - [null]
2022-08-30 20:17:53.008 TRACE 17488 --- [nio-8081-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [BIGINT] - [20001]
2022-08-30 20:17:53.012 WARN 17488 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2022-08-30 20:17:53.012 ERROR 17488 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: NULL value in column »owner_id« of relation »option_group« violates Not-Null-Constraint
If I would have defined cascade delete on the owner field I could imagine that hibernate might delete the owner first, set the owner in the OptionGroup to null and then delete the OptionGroup - although it does not make much sense to first the the owner to null and then delete the OptionGroup...
Do you have any idea why hibernate is setting owner_id to null?
Btw. if I remove the NotNull constraint the behavior is as expected: the OptionGroup is deleted and the User (owner) remains.
This is the OptionGroupClass:
#Entity
#Table(name = "option_group"/*, uniqueConstraints = {
#UniqueConstraint(columnNames = { "owner_id", "option_group_name" }) }*/)
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class OptionGroup {
/**
* Id of the Option Group. Generated by the database
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* Name of the Option Group. Unique in the context of a user.
*/
#NotBlank(message = "Option Group name is mandatory")
#Column(name = "option_group_name")
private String optionGroupName;
/**
* Description for the Option Group
*/
private String description;
/**
* User that is the owner of the Option Group.
*/
#NotNull(message = "Owner cannot be null")
#ManyToOne(fetch = FetchType.LAZY, cascade={CascadeType.PERSIST})
#JoinColumn(name = "ownerId")
private User owner;
/**
* List of options that belong to the Option Group.
*/
#OneToMany(cascade = CascadeType.ALL, mappedBy = "optionGroup", orphanRemoval = true)
#NotEmpty(message = "Options cannot be empty")
private List<Option> options;
/**
* List of invitations that belong to the Option Group.
*/
#OneToMany(cascade = CascadeType.ALL, mappedBy = "optionGroup", orphanRemoval = true)
private List<Invitation> invitations;
#Override
public int hashCode() {
return Objects.hash(description, id, optionGroupName,
options == null ? null : options.stream().map(option -> option.getId()).toList(), owner,
invitations == null ? null : invitations.stream().map(invitation -> invitation.getId()).toList());
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OptionGroup other = (OptionGroup) obj;
return Objects.equals(description, other.description) && Objects.equals(id, other.id)
&& Objects.equals(optionGroupName, other.optionGroupName)
&& Objects.equals(options == null ? null : options.stream().map(option -> option.getId()).toList(),
other.options == null ? null : other.options.stream().map(option -> option.getId()).toList())
&& Objects.equals(owner, other.owner)
&& Objects.equals(
invitations == null ? null
: invitations.stream().map(invitation -> invitation.getId()).toList(),
other.invitations == null ? null
: other.invitations.stream().map(invitation -> invitation.getId()).toList());
}
#Override
public String toString() {
return "OptionGroup [id=" + id + ", optionGroupName=" + optionGroupName + ", description=" + description
+ ", owner=" + owner + ", options="
+ (options == null ? null : options.stream().map(option -> option.getId()).toList()) + ", invitations="
+ (invitations == null ? null : invitations.stream().map(invitation -> invitation.getId()).toList())
+ "]";
}
}
As you can see the cascade of owner is limited to persist. f a OptionGroup is created, the owner User is created as well. But if an OptionGroup is deleted the owner User should not be deleted.
This is the User class:
/**
* Entity that represents a user
*
* Primary key: id
*/
#Entity
#Table(name = "usert", uniqueConstraints = {
#UniqueConstraint(columnNames = { "email"}) })
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class User {
/**
* Id of the User. Generated by the database
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* Email address of the invitee.
*/
#Email(message = "Email is not valid", regexp = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])")
private String email;
/**
* Option Groups of which the user is the owner.
*/
#OneToMany(cascade = CascadeType.ALL, mappedBy = "owner", orphanRemoval = true)
private List<OptionGroup> ownedOptionGroups;
/**
* Invitations of the user.
*/
#OneToMany(cascade = CascadeType.ALL, mappedBy = "invitee", orphanRemoval = true)
private List<Invitation> invitations;
}
And this is the class that triggers the delete
/**
* Service related to Option Groups.
*/
#Service
#Transactional
#AllArgsConstructor
public class OptionGroupService {
/**
* Repository used to access Option Groups.
*/
#Autowired
private OptionGroupRepository optionGroupRepository;
/**
* Deletes the Option Group with the given id.
*
* #param id Id of the Option Group to delete.
* #throws ObjectWithNameDoesNotExistException
* #throws ObjectWithIdDoesNotExistException
*/
public void deleteOptionGroupById(Long id) throws ObjectWithIdDoesNotExistException {
if (optionGroupRepository.existsById(id)) {
optionGroupRepository.deleteById(id);
} else {
throw new ObjectWithIdDoesNotExistException("Option Group", id);
}
}
}
And the repository
public interface OptionGroupRepository extends JpaRepository<OptionGroup, Long> {}
Appreciate your help on this. Thanks.
The root cause was an extensive use of cascades in both, parent and child entities which led to a chain of cascades: by saving an Option Group an Invitation was saved by which again an Option Group was saved. After cleaning this up it works.
I recommend reading: Hibernate - how to use cascade in relations correctly
I have very strange issue here. I am using composite primary key with #IdClass in my entities. It is working fine in every case, except save. After saving the entity, JPA is not firing SELECT query to select inserted data, and not merging the result. Though data is getting saved in database successfully. Also there are no errors. Below is some of the code which can help in debugging the issue:
AbstractEntity.java
#MappedSuperclass
#IdClass(PrimaryKey.class)
public abstract class AbstractEntity implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -1191422925622832672L;
/** The id. */
private String id;
...
/**
* Gets the id.
*
* #return the id
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public String getId() {
return id;
}
...
}
PrimaryKey.java
public class PrimaryKey implements Serializable {
/** The id. */
private String id;
/**
* Gets the id.
*
* #return the id
*/
#Column(name = "id")
#Convert(converter = CryptoConverter.class)
public String getId() {
return id;
}
...
}
User.java
#Entity
#Table(name = "user")
public class User extends AbstractEntity {
...
}
UserRepository.java
#Repository
public interface UserRepository extends CrudRepository<User, PrimaryKey> {
}
I have BigInt autoIncrement Id in database as primary key. But I want to expose it in encrypted form to outside world, so I have used #Converter to encrypt and decrypt it.
When I invoke userRepository.save(userEntity) from UserService, it persists the data, but does not return generated id from database.
How can I resolve this issue?
EDIT:
I have hosted demo project with this functionality here.
Since I am not seeing anywhere in your code, you need to specify Id, the strategy type and the column on the database.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "applicant_id")
is it possible to query values from set? for example,
public class Employee implements Serializable {
/** Person ID (indexed). */
#QuerySqlField(index = true)
private long id;
/** Department ID (indexed). */
#QuerySqlField(index = true)
private Set deptIds;
/** First name (not-indexed). */
#QuerySqlField
private String firstName;
/** Last name (not indexed). */
#QuerySqlField
private String lastName;
}
now i want to get all employee for one particular department.
It is possible with Scan queries, but not possible with SQL queries.
Looks like you use SQL queries. In this case you have to think in terms of relational databases. There is a many-to-many relationship between Employee and Department, so you have to add a Junction Table.
public class EmployeeDepartment implements Serializable {
/** Person ID (indexed). */
#QuerySqlField(index = true)
private long personId;
/** Department ID (indexed). */
#QuerySqlField(index = true)
private long deptId;
}
After that you can do a three way join to find employees for a particular department.
When I am having only 1 onetoMany relation code works fine. When I declare more that 1 #onetomany relation in an entity its breaks saying : org.hibernate.exception.SQLGrammarException: Unknown column 'userregist0_.jdoDetachedState' in 'field list' How this can be managed MY entity class is: package com.bullbeardevice.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The persistent class for the user_registration database table.
*
*/
#Entity
#Table(name = "user_registration")
#NamedQuery(name = "UserRegistration.findAll", query = "SELECT u FROM UserRegistration u")
#PersistenceCapable(identityType=IdentityType.APPLICATION, detachable="false")
public class UserRegistration implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_Registration_Id")
private String userRegistrationId;
#Column(name = "account_Status")
private int accountStatus;
#Column(name = "created_By")
private String createdBy;
#Column(name = "created_On")
#Temporal(TemporalType.TIMESTAMP)
private Date createdOn;
#Column(name = "email_Address")
private String emailAddress;
#Column(name = "expiry_Date")
#Temporal(TemporalType.TIMESTAMP)
private Date expiryDate;
#ManyToOne
#JoinColumn(name = "Group_Master_Id")
private GroupMaster groupMaster;
#Column(name = "modified_By")
private String modifiedBy;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "modified_On")
private Date modifiedOn;
#Column(name = "user_password")
private String password;
#Column(name = "permissions")
private int permissions;
// bi-directional many-to-one association to Chat
#OneToMany(mappedBy = "userRegistration")
private List<Chat> chats;
// bi-directional many-to-one association to Coupon
#OneToMany(mappedBy = "userRegistration")
private List<Coupon> coupons;
// bi-directional many-to-one association to DeviceDetail
#OneToMany(mappedBy = "userRegistration")
private List<DeviceDetail> deviceDetails;
// bi-directional many-to-one association to Portfolio
#OneToMany(mappedBy = "userRegistration")
private List<Portfolio> portfolios;
// bi-directional many-to-one association to UserDetail
#OneToMany(mappedBy = "userRegistration")
private List<UserDetail> userDetails;
// bi-directional many-to-one association to UserLoginDetail
#OneToMany(mappedBy = "userRegistration")
private List<UserLoginDetail> userLoginDetails;
// bi-directional many-to-one association to UserRoleMaster
#ManyToOne
#JoinColumn(name = "User_Role_Master_Id")
private UserRoleMaster userRoleMaster;
// bi-directional many-to-one association to Watch
#OneToMany(mappedBy = "userRegistration")
private List<Watch> watches;
public UserRegistration() {
}
/**
* #return the userRegistrationId
*/
public String getUserRegistrationId() {
return userRegistrationId;
}
/**
* #param userRegistrationId
* the userRegistrationId to set
*/
public void setUserRegistrationId(String userRegistrationId) {
this.userRegistrationId = userRegistrationId;
}
/**
* #return the accountStatus
*/
public int getAccountStatus() {
return accountStatus;
}
/**
* #param accountStatus
* the accountStatus to set
*/
public void setAccountStatus(int accountStatus) {
this.accountStatus = accountStatus;
}
/**
* #return the createdBy
*/
public String getCreatedBy() {
return createdBy;
}
/**
* #param createdBy
* the createdBy to set
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/**
* #return the createdOn
*/
public Date getCreatedOn() {
return createdOn;
}
/**
* #param createdOn
* the createdOn to set
*/
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
/**
* #return the emailAddress
*/
public String getEmailAddress() {
return emailAddress;
}
/**
* #param emailAddress
* the emailAddress to set
*/
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
/**
* #return the expiryDate
*/
public Date getExpiryDate() {
return expiryDate;
}
/**
* #param expiryDate
* the expiryDate to set
*/
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
/**
* #return the groupMaster
*/
public GroupMaster getGroupMaster() {
return groupMaster;
}
/**
* #param groupMaster
* the groupMaster to set
*/
public void setGroupMaster(GroupMaster groupMaster) {
this.groupMaster = groupMaster;
}
/**
* #return the modifiedBy
*/
public String getModifiedBy() {
return modifiedBy;
}
/**
* #param modifiedBy
* the modifiedBy to set
*/
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
/**
* #return the modifiedOn
*/
public Date getModifiedOn() {
return modifiedOn;
}
/**
* #param modifiedOn
* the modifiedOn to set
*/
public void setModifiedOn(Date modifiedOn) {
this.modifiedOn = modifiedOn;
}
/**
* #return the password
*/
public String getPassword() {
return password;
}
/**
* #param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* #return the permissions
*/
public int getPermissions() {
return permissions;
}
/**
* #param permissions
* the permissions to set
*/
public void setPermissions(int permissions) {
this.permissions = permissions;
}
/**
* #return the chats
*/
public List<Chat> getChats() {
return chats;
}
/**
* #param chats
* the chats to set
*/
public void setChats(List<Chat> chats) {
this.chats = chats;
}
public Chat addChat(Chat chat) {
getChats().add(chat);
chat.setUserRegistration(this);
return chat;
}
public Chat removeChat(Chat chat) {
getChats().remove(chat);
chat.setUserRegistration(null);
return chat;
}
public List<Coupon> getCoupons() {
return this.coupons;
}
public void setCoupons(List<Coupon> coupons) {
this.coupons = coupons;
}
public Coupon addCoupon(Coupon coupon) {
getCoupons().add(coupon);
coupon.setUserRegistration(this);
return coupon;
}
public Coupon removeCoupon(Coupon coupon) {
getCoupons().remove(coupon);
coupon.setUserRegistration(null);
return coupon;
}
public List<DeviceDetail> getDeviceDetails() {
return this.deviceDetails;
}
public void setDeviceDetails(List<DeviceDetail> deviceDetails) {
this.deviceDetails = deviceDetails;
}
public DeviceDetail addDeviceDetail(DeviceDetail deviceDetail) {
getDeviceDetails().add(deviceDetail);
deviceDetail.setUserRegistration(this);
return deviceDetail;
}
public DeviceDetail removeDeviceDetail(DeviceDetail deviceDetail) {
getDeviceDetails().remove(deviceDetail);
deviceDetail.setUserRegistration(null);
return deviceDetail;
}
public List<Portfolio> getPortfolios() {
return this.portfolios;
}
public void setPortfolios(List<Portfolio> portfolios) {
this.portfolios = portfolios;
}
public Portfolio addPortfolio(Portfolio portfolio) {
getPortfolios().add(portfolio);
portfolio.setUserRegistration(this);
return portfolio;
}
public Portfolio removePortfolio(Portfolio portfolio) {
getPortfolios().remove(portfolio);
portfolio.setUserRegistration(null);
return portfolio;
}
public List<UserDetail> getUserDetails() {
return this.userDetails;
}
public void setUserDetails(List<UserDetail> userDetails) {
this.userDetails = userDetails;
}
public UserDetail addUserDetail(UserDetail userDetail) {
getUserDetails().add(userDetail);
userDetail.setUserRegistration(this);
return userDetail;
}
public UserDetail removeUserDetail(UserDetail userDetail) {
getUserDetails().remove(userDetail);
userDetail.setUserRegistration(null);
return userDetail;
}
public List<UserLoginDetail> getUserLoginDetails() {
return this.userLoginDetails;
}
public void setUserLoginDetails(List<UserLoginDetail> userLoginDetails) {
this.userLoginDetails = userLoginDetails;
}
public UserLoginDetail addUserLoginDetail(UserLoginDetail userLoginDetail) {
getUserLoginDetails().add(userLoginDetail);
userLoginDetail.setUserRegistration(this);
return userLoginDetail;
}
public UserLoginDetail removeUserLoginDetail(UserLoginDetail userLoginDetail) {
getUserLoginDetails().remove(userLoginDetail);
userLoginDetail.setUserRegistration(null);
return userLoginDetail;
}
public UserRoleMaster getUserRoleMaster() {
return this.userRoleMaster;
}
public void setUserRoleMaster(UserRoleMaster userRoleMaster) {
this.userRoleMaster = userRoleMaster;
}
public List<Watch> getWatches() {
return this.watches;
}
public void setWatches(List<Watch> watches) {
this.watches = watches;
}
public Watch addWatch(Watch watch) {
getWatches().add(watch);
watch.setUserRegistration(this);
return watch;
}
public Watch removeWatch(Watch watch) {
getWatches().remove(watch);
watch.setUserRegistration(null);
return watch;
}
}
Please help. Thanks in advance!
With app-engine, you don't need hibernate. Most JPA annotations that you use with hibernate, are natively supported in app-engine. I believe you should not be mixing JDO (javax.jdo) and JPA(javax.persistence).