I have been getting an error while trying to update a list of entities (Job):
Multiple representations of the same entity [com.introlabsystems.upworkscraper.model.entities.Skill#42] are being merged. Detached: [Skill(id=42, skillName=Web Scraping)]; Detached: [Skill(id=42, skillName=Web Scraping)]
I think it is in case that three entities have ManyToMany relationship with Skill entity.
#Entity
public class Job {
#Id
#Column(unique = true, nullable = false)
#SerializedName(value = "ciphertext")
private String id;
#Column(length = 2048)
private String title;
#Column(columnDefinition = "TEXT")
#JsonAdapter(value = DescriptionAdapter.class)
private String description;
#SerializedName(value = "subcategory2")
private String category;
#ManyToMany(cascade = {
CascadeType.MERGE
}, fetch = FetchType.EAGER)
#JoinTable(
joinColumns = {#JoinColumn(name = "job_id")},
inverseJoinColumns = {#JoinColumn(name = "skill_id")}
)
#JsonAdapter(value = SkillsAdapter.class)
private Set<Skill> skills;
private String duration;
private String engagement;
#JsonAdapter(value = AmountAdapter.class)
private String amount;
#JsonAdapter(value = AmountAdapter.class)
private String maxAmount;
private String freelancersToHire;
private String enterpriseJob;
private String proposalsTier;
private String stickyLabel;
#SerializedName(value = "tierLabel")
private String tier;
#JsonAdapter(value = DateTimeAdapter.class)
private LocalDateTime createdOn;
#JsonAdapter(value = DateTimeAdapter.class)
private LocalDateTime publishedOn;
#JsonAdapter(value = DateTimeAdapter.class)
private LocalDateTime renewedOn;
private LocalDateTime hiredOn;
#OneToOne(cascade = CascadeType.ALL)
private Contract contract;
#SerializedName(value = "type")
#JsonAdapter(value = JobTypeAdapter.class)
#Enumerated(value = EnumType.STRING)
private JobType jobType;
#Enumerated(value = EnumType.STRING)
private JobStatus jobStatus = JobStatus.OPEN;
private String projectStage;
private String ongoingProject;
private String projectType;
private String finalOutput;
private String Platform;
private String oneTimeProject;
private String jobSuccessScore;
private String includeRisingTalent;
private String englishLevel;
private String upworkHours;
private String freelancerType;
private String preferredLocation;
private String interviewing;
#OneToOne(cascade = CascadeType.ALL)
private PrivateStatus privateStatus;
}
#Data
#Entity
public class Skill {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String skillName;
}
#Data
#Entity
public class Contract {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#JsonAdapter(value = ContractJobIdAdapter.class)
#SerializedName(value = "jobInfo")
private String jobId;
private String totalCharge;
private String totalHours;
#JsonAdapter(value = AmountAdapter.class)
private String rate;
#JsonAdapter(value = DateTimeAdapter.class)
private LocalDateTime startDate;
#JsonAdapter(value = DateTimeAdapter.class)
private LocalDateTime endDate;
#ManyToOne(cascade = CascadeType.MERGE)
#SerializedName(value = "contractorInfo")
private Freelancer freelancer;
#ManyToOne(cascade = CascadeType.ALL)
private Client client;
}
#Data
#Entity
public class Freelancer {
#Id
#SerializedName(value = "ciphertext")
private String id;
#SerializedName(value = "contractorName")
private String name;
#Column(length = 2048)
private String title;
#Column(columnDefinition = "TEXT")
#JsonAdapter(value = DescriptionAdapter.class)
private String description;
#JsonAdapter(value = FreelancerLocationAdapter.class)
private String location;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
joinColumns = {#JoinColumn(name = "freelancer_id")},
inverseJoinColumns = {#JoinColumn(name = "skill_id")}
)
#JsonAdapter(value = SkillsAdapter.class)
private Set<Skill> skills;
private String hourlyRate;
private String privateFeedbackHireAgain;
private String rating;
private String scores;
private String totalEarnings;
private String totalFeedback;
private String totalFixedJobs;
private String totalHourlyJobs;
private String totalHours;
private String totalJobsWorked;
private String topRatedStatus;
private String successScore;
#OneToMany(cascade = CascadeType.ALL)
private List<ContractHistory> contractHistories;
#ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(
joinColumns = {#JoinColumn(name = "freelancer_id")},
inverseJoinColumns = {#JoinColumn(name = "agency_id")}
)
private Set<Agency> agency;
}
#Data
#Entity
public class Agency {
#Id
#SerializedName(value = "chipertext")
private String id;
#JsonAdapter(value = AmountAdapter.class)
private String minRate;
#JsonAdapter(value = AmountAdapter.class)
private String maxRate;
private String city;
private String country;
#Column(columnDefinition = "TEXT")
#JsonAdapter(value = DescriptionAdapter.class)
private String description;
private String jobSuccessScore;
private String name;
#Column(length = 2048)
private String title;
private String topRatedStatus;
private String totalEarnings;
private String totalHours;
private String totalJobs;
private String recentEarnings;
private String averageRecentEarnings;
#JsonAdapter(value = DateTimeAdapter.class)
private LocalDateTime memberSince;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
joinColumns = {#JoinColumn(name = "agency_id")},
inverseJoinColumns = {#JoinColumn(name = "skill_id")}
)
#JsonAdapter(value = SkillsAdapter.class)
private Set<Skill> skills;
}
I trying to save a job. Before do it I get skills from job, agency, freelancer, trying to search them in DB and substitute ids.
for (Skill skill: skills)
{
Skill skillWithID =
skillDataService.findBySkillName(skill.getSkillName())
.orElseGet(() -> skillDataService.save(skill));
skill.setId(skillWithID.getId());
}
Changed
CascadeType.MERGE
to
CascadeType.PERSIST,
CascadeType.DETACH,
CascadeType.REFRESH,
CascadeType.REMOVE
and it works
you are facing this issue because you are adding the object to the list which is already available.while performing save operation with oneToMany mapping
Now removing CascadeType.MERGE from cascade is one solution but not a best solution because after removing MERGE from Cascade you won't be able to update the mapped object ever
If you want to perform update operation also along with save for the mapped objects then before adding mapped object to list/collection just check/search within the list for the object and if the mapped object is available within the list then perform operation on that particular object.
check my other post for example
Related
I developed a microservice and when I go to get to postman ( http://localhost:8080/user/utenti/ ) I get this error InvalidDefinitionException No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.application.dto.UserDto["applicationRoleID"]->com.poste.anagrafica.entity.Role$HibernateProxy$N0iZZA2I["hibernateLazyInitializer"])
Can you help me please?
For clarity I enclose the schema of the database and the classes entity , dto and controller
The Entity classes
"""
#Entity
#Table(name = "USERS")
#Data
#NoArgsConstructor
#AllArgsConstructor
#Getter
#Setter
public class User implements Serializable {
#Id
#Column(name = "user_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "created_date")
private LocalDateTime createdDate;
#Column(name = "deleted", nullable = false)
private Long number;
#Column(name = "modified_date")
private LocalDateTime modifiedDate;
#Column(name = "birth_place")
private String birthPlace;
#Column(name = "birthday")
private Date birthDay;
#Column(name = "canNominate")
private Long canNominate;
#Column(name = "email")
private String email;
#Column(name = "firstName")
private String firstName;
#Column(name= "fiscalCode")
private String fiscalCode;
#Column(name = "hiringDate")
private Date hiringDate;
#Column(name ="last_name")
private String lastName;
#Column(name = "matricola")
private String matricola;
#Column(name = "position")
private String position;
#Column(name = "registration_number")
private String registrationNumber;
#Column(name = "replaced")
private Long replaced;
#Column(name = "terminationDate")
private Date terminationDate;
#Column(name = "user_status")
private String userStatus;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "application_role_id")
private Role applicationRoleID;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "company_id")
private Company companyID;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "direction_id")
private Direction directions ;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "level_id")
private Levels levelID;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "referent_id")
private User referentID;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "role_id")
private Role roleID;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "task_id")
private EmployeeTask taskID;
}
"""
the UserDTO class
"""
#Data
public class UserDto {
private Long userId;
private LocalDateTime createdDate;
private Long number;
private LocalDateTime modifiedDate;
private String birthPlace;
private Date birthDay;
private Long canNominate;
private String email;
private String firstName;
private String fiscalCode;
private Date hiringDate;
private String lastName;
private String matricola;
private String position;
private String registrationNumber;
private Long replaced;
private Date terminationDate;
private String userStatus;
private Role applicationRoleID;
private Company companyID;
private Direction directions ;
private Levels levelID;
private User referentID;
private Role role;
private EmployeeTask taskID;
}
"""
the controller class
"""
#RestController
#RequestMapping("/user")
#Log
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
#Autowired
UserService userService;
#GetMapping(value = "/cerca/{registration_number}", produces = "application/json")
public ResponseEntity<List<UserDto>> listUserByRegistrationNumber(#PathVariable("registration_number") String registrationNumber)
throws ChangeSetPersister.NotFoundException
{
log.info("****** Ottengo l'user con numeroRegistrazione " + registrationNumber + " *******");
List<UserDto> user = userService.SelByRegistrationNumber(registrationNumber);
return new ResponseEntity<List<UserDto>>(user, HttpStatus.OK);
}
#GetMapping(value = "/utenti", produces = "application/json")
public ResponseEntity<List<UserDto>> listAllUsers ()throws ChangeSetPersister.NotFoundException{
List<UserDto> user = userService.SelTutti();
return new ResponseEntity<List<UserDto>>(user, HttpStatus.OK);
}
}
"""
the application.properties
"""
spring.datasource.url = jdbc:oracle:thin:#192.134.2.82:1521/orcl
spring.datasource.username =admin
spring.datasource.password =zzzx
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
# JPA settings
spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect
spring.jpa.hibernate.use-new-id-generator-mappings=false
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.implicit- strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
"""
You can try
spring.jackson.serialization.fail-on-empty-beans=false
in your application.properties.
I want to return a Profile Object in JSON containing a list of login details associated with a social network.
Everything works correctly when the "reseaux_sociaux" table is empty. For my status table I get my statuses in JSON format in my Profile object. However, when "reseaux_sociaux" contains values then I get the error below and my Profile object in JSON format is not returned...
(Logs)
https://cloudvyzor.com/logpad/?query&database=sandbox-7fb06b2c06f198a7c0e4ff7c74d659e0
Profil Class
#Entity
#Table(name = "Profil")
public class Profil {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "IdComptes", nullable = false)
private Comptes IdComptes;
private String Avatar;
private String Banniere;
private String Pseudo;
private String MailPro;
private String Bio;
#ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinTable(name = "Statut_Profil", joinColumns = #JoinColumn(referencedColumnName = "Id"),inverseJoinColumns = #JoinColumn(referencedColumnName ="Id"))
private List<Statut> Statut;
#OneToMany( mappedBy = "IdProfil")
#JsonManagedReference("id_profil")
private List<ReseauxSociaux> Reseaux;
public Profil(){}
public Profil(Long id, Comptes idComptes, String avatar, String banniere, String pseudo, String mailPro, String bio) {
Id = id;
IdComptes = idComptes;
Avatar = avatar;
Banniere = banniere;
Pseudo = pseudo;
MailPro = mailPro;
Bio = bio;
}
}
ReseauxSociaux Class
#Entity
#IdClass(ReseauxId.class)
public class ReseauxSociaux {
#Id
private int Id;
#Id
private Long IdProfil;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "IdProfil", insertable = false, updatable = false)
#JsonBackReference("id_profil")
private Profil Profil;
#ManyToOne
#JoinColumn(name = "Id", insertable = false, updatable = false)
#JsonBackReference("id")
private Reseau Reseau;
private String Identifiant;
private ReseauxSociaux()
{}
public ReseauxSociaux(int id, Long idProfil, String identifiant) {
Id = id;
IdProfil = idProfil;
Identifiant = identifiant;
}
}
Reseau class
#Entity
public class Reseau {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int Id;
private String Nom;
private String Couleur;
//I tried it with and without and it made no difference
#OneToMany( mappedBy = "Id")
#JsonManagedReference("id")
private List<ReseauxSociaux> Reseaux;
public Reseau(){}
public Reseau(int id, String nom, String couleur) {
Id = id;
Nom = nom;
Couleur = couleur;
}
//Get Set
}
Profil Controller
#RestController
#RequestMapping("/profil")
public class ProfilController {
private final ProfilRepository profilRepository;
public ProfilController(ProfilRepository profilRepository) {
this.profilRepository = profilRepository;
}
#PostMapping("/getprofil/{idCompte}")
Profil GetProfil(#PathVariable("idCompte") Long idCompte)
{
Profil profil= profilRepository.findProfilById(idCompte);
return profil;
}
}
I finally succeeded... The cause of the problem remains unclear but I have two hypotheses: the first is the use of capital letters on variable names; the second is the use of a list with the onetomany with the same name in two entities.
Profil class
#Entity
#Table(name = "Profil")
public class Profil {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "idComptes", nullable = false)
#JsonBackReference("id_comptes")
private Comptes idComptes;
private String avatar;
private String banniere;
private String pseudo;
private String mailPro;
private String bio;
#ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinTable(name = "statut_profil", joinColumns = #JoinColumn(referencedColumnName = "id"),inverseJoinColumns = #JoinColumn(referencedColumnName ="id"))
private List<Statut> statut;
#OneToMany( mappedBy = "idProfil")
#JsonManagedReference("id_profil")
private List<ReseauxSociaux> lstprofil;
public Profil(){}
public Profil(Long id, Comptes idComptes, String avatar, String banniere, String pseudo, String mailPro, String bio) {
this.id = id;
this.idComptes = idComptes;
this.avatar = avatar;
this.banniere = banniere;
this.pseudo = pseudo;
this.mailPro = mailPro;
this.bio = bio;
}
//get set
}
ReseauxSociaux class
#Entity
#IdClass(ReseauxId.class)
public class ReseauxSociaux {
#Id
private int id;
#ManyToOne
#JoinColumn(name = "id", insertable = false, updatable = false)
#JsonBackReference("id_reseau")
private Reseau reseau;
#Id
private Long idProfil;
#ManyToOne
#JoinColumn(name = "idProfil", insertable = false, updatable = false)
#JsonBackReference("id_profil")
private Profil profil;
private String identifiant;
private ReseauxSociaux()
{}
public ReseauxSociaux(int id, Reseau reseau, Long idProfil, String identifiant) {
this.id = id;
this.reseau = reseau;
this.idProfil = idProfil;
this.identifiant = identifiant;
}
}
Reseau class
#Entity
public class Reseau {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String nom;
private String couleur;
#OneToMany( mappedBy = "id")
#JsonManagedReference("id_reseau")
private List<ReseauxSociaux> lstreseau;
public Reseau(){}
public Reseau(int id, String nom, String couleur) {
this.id = id;
this.nom = nom;
this.couleur = couleur;
}
}
I created my app using JHipster. When i try to get list of tournaments via TournamentQueryService i get this error :
Exception in TournamentQueryService.findByCriteria() with cause =
'org.hibernate.HibernateException: Unable to access lob stream' and
exception = 'Unable to access lob stream; nested exception is
org.hibernate.HibernateException: Unable to access lob stream'
This is filter and Page object :
find by criteria : TournamentCriteria{}, page: Page request [number:
0, size 8, sort: startDate: DESC]
So it just gets 8 first tournaments.
This is tournament class :
#Entity
#Table(name = "tournament")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "tournament")
public class Tournament extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "location")
private String location;
#Column(name = "url")
private String url;
#Column(name = "start_date")
private ZonedDateTime startDate;
#Column(name = "end_date")
private ZonedDateTime endDate;
#Column(name = "entry_fee")
private Double entryFee;
#Column(name = "prize")
private Double prize;
#Column(name = "goods")
private String goods;
#Column(name = "favorite_rating")
private Long favoriteRating;
#Column(name = "participants_number")
private Integer participantsNumber;
#Column(name = "finished")
private Boolean finished;
#Column(name = "view_only")
private Boolean viewOnly;
#Column(name = "image")
private String image;
#Column(name = "description")
private String description;
#Column(name = "teams_applied")
private String teamsApplied;
#Lob
#Column(name = "schedule")
private String schedule;
#Lob
#Column(name = "prize_distribution")
private String prizeDistribution;
#Lob
#Column(name = "contacts")
private String contacts;
#Lob
#Column(name = "rules")
private String rules;
#OneToMany(mappedBy = "tournament", fetch = FetchType.LAZY)
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Stream> streams = new HashSet<>();
#ManyToMany(fetch = FetchType.EAGER)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#JoinTable(name = "tournament_platforms", joinColumns = #JoinColumn(name = "tournaments_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "platforms_id", referencedColumnName = "id"))
private Set<Platform> platforms = new HashSet<>();
#ManyToOne
private Game game;
#ManyToOne
private TournamentStatus status;
#ManyToOne(fetch = FetchType.LAZY)
private EntryType entryType;
#ManyToOne(fetch = FetchType.LAZY)
private TournamentFormat format;
#ManyToOne
private Region region;
#ManyToOne(fetch = FetchType.LAZY)
private GameMode gameMode;
#ManyToOne(fetch = FetchType.LAZY)
private PrizeType prizeType;
#ManyToOne
private Organizer organizer;
#ManyToOne(fetch = FetchType.LAZY)
private TournamentStage stage;
#ManyToOne
private HostPlatform hostPlatforms;
#ManyToOne(fetch = FetchType.LAZY)
private TournamentType type;
#ManyToOne
private PlayType playType;
#ManyToOne
private Currency currency;
#ManyToOne
private Country country;
Here is the method that calls hibernate :
#Transactional(readOnly = true)
public Page<Tournament> findByCriteria(TournamentCriteria criteria, Pageable page) {
log.info("find by criteria : {}, page: {}", criteria, page);
final Specifications<Tournament> specification = createSpecification(criteria);
Page<Tournament> result = tournamentRepository.findAll(specification, page);
return result;
}
Is it possibile that you are trying to access Lob properties when hiberante session is closed?
Try to replace your #Lob properties with the following:
#Basic(fetch=FetchType.EAGER) #Lob
and check if the error persists.
I have small application which is responsible for saving data in database. I'm using Hibernate for this purpose. Below is my code:
User class
#Entity
#Table(name = "USERS")
#Transactional
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USER_ID")
private int userId;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "SURNAME")
private String surname;
#Column(name = "AGE")
private int age;
#Column(name = "EMAIL")
private String email;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
private Address address;
public User() {
}
public User(String firstName, String secondName, int age, String email) {
this.firstName = firstName;
this.surname = secondName;
this.age = age;
this.email = email;
}
// GETTERS/SETTERS
Address class
#Entity
#Table(name = "ADDRESS")
#Transactional
public class Address implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#GenericGenerator(name = "generator", strategy = "foreign", parameters = #Parameter(name = "property", value = "user"))
#Id
#GeneratedValue(generator = "generator")
#Column(name = "USER_ID", unique = true, nullable = false)
private int addressId;
#Column(name = "STREET")
private String street;
#Column(name = "STREET_NUMBER")
private String streetNumber;
#Column(name = "FLAT_NUMBER")
private String flatNumber;
#Column(name = "POSTAL_CODE")
private String postalCode;
#Column(name = "CITY")
private String city;
#Column(name = "COUNTRY")
private String country;
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn(name = "USER_ID")
private User user;
public Address() {
}
public Address(String street, String streetNumber, String flatNumber, String postalCode, String city, String country) {
this.street = street;
this.streetNumber = streetNumber;
this.flatNumber = flatNumber;
this.postalCode = postalCode;
this.city = city;
this.country = country;
}
//GETTERS/SETTERS
And when I perform save() method which is responsible for saving data in this two tables only users table is filled up.
I found this solution Hibernate #OneToOne with Shared Primary Key(bidirectional). Dependent entity not persisted in DB.
but it doesn't work for me.
I'm using:
Hibernate 4.3.6.Final
Spring 4.3.6.RELEASE
Your Address class should be coded as follows (assuming that Address should be created with the same Id as the User where the id is generated):
#Id
#Column(name = "USER_ID", unique = true, nullable = false)
private int addressId;
#MapsId
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "USER_ID", referencedColumnName = "USER_ID")
private User user;
During Persist
User u = new User();
// populate u fields
Address a = new Address();
a.setUser(u);
// populate a fields
session.persist(a);
I have been using many to many mapping here is my POJO classes.
Menu.java :
#Entity
#Table(name = "menu")
public class Menu {
#Id
#Column(name = "menuid")
#GeneratedValue
private int menuid;
#Column(name = "parentid")
private int parentid;
#Column(name = "menuname")
private String menuname;
#Column(name = "url")
private String url;
#Column(name = "status")
private String status;
#Column(name = "usertype")
private String usertype;
#Column(name = "isparent")
private boolean isParent;
private ArrayList<Menu> childMenu;
#ManyToMany(mappedBy="menus")
private List<User> users;
public Menu(Integer menuid){
this.menuid=menuid;
}
public Menu(){
}
User.java :
#Entity
#Table(name = "user")
public class User implements Serializable {
#Id
#Column(name = "userid")
#GeneratedValue
private Integer userId;
#Column(name = "OUTLET_ID")
private int outletId;
#Column(name = "NAME")
private String name;
#Column(name = "USERTYPE")
private String userType;
#Column(name = "LOGINID")
private String loginId;
#Column(name = "PASSWORD")
private String password;
#Column(name = "CREATEDDATE")
private String createdDate;
#Column(name = "CONTACTNUMBER")
private String contactNumber;
#Column(name = "EMAILID")
private String emailId;
#Column(name = "OUTLETTYPE")
private String outlettype;
#Transient
private String nsec;
#javax.persistence.Transient
ArrayList<Integer> menuid;
#javax.persistence.Transient
ArrayList<Long> clientid;
#javax.persistence.Transient
ArrayList<String> clientName;
#ManyToMany(fetch=FetchType.EAGER) #JsonIgnore
#JoinTable(name="user_menu",joinColumns={#JoinColumn(name="userid")},
inverseJoinColumns={#JoinColumn(name="menuid")})
public List<Menu> menus;
#ManyToMany(fetch=FetchType.EAGER) #JsonIgnore
#JoinTable(name="user_client",joinColumns={#JoinColumn(name="userid")},
inverseJoinColumns={#JoinColumn(name="outletid")})
public List<Client> clients;
public User() {
}
I have user,menu and third mapping table user_menu which is created automatically, I successfully get result when fire following query in mysql
select * from menu m inner join user_menu um on m.menuid = um.menuid where um.userid = 41;
I want to write this query in hibernate how to this stuff ???
Finally I find my answer, here is my hql query,
String sql = "select m.menuid as menuid,m.parentid as parentid,m.menuname as menuname,m.url as url,m.status as status,m.usertype as usertype,m.isParent as isParent,m.childMenu as childMenu from Menu m join m.users u where u.userId = "+userid +"";
q = session.createQuery(sql).setResultTransformer(Transformers.aliasToBean(Menu.class));