Trouble executing an JPQL query - mysql

I'm working with spring boot entity manger using JPQL with queries.
The following query is working correctly:
SELECT h, uh FROM Hour h, UserHour uh
But now I want to get a single result for which I use the query:
SELECT h FROM Hour h INNER JOIN UserHour uh WHERE uh.userId = 1
But then the results are zero, which is not expected.
But, when I use the SQL query:
SELECT * FROM hour
INNER JOIN user_hour
ON user_hour.hour_id = hour.hour_id
WHERE user_hour.user_id = '1'
I get the result I want.
Please help me out.
EDIT:
List<Object> result = entityManager.createQuery(
"select distinct hr " +
"from Hour hr " +
"join hr.users hu " +
"where hu.id = :userID")
.setParameter( "userID", 1)
.getResultList();
System.out.println(result);
User Entity:
package com.timely.backend.models;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
#Entity
#Table(name = "USER")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String fullname;
private String email;
private String creation_date;
// user roles
#ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
#CollectionTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"))
#Enumerated(EnumType.STRING)
private Set<Role> roles;
#ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "user_hour",
joinColumns = #JoinColumn(name = "userId"),
inverseJoinColumns = #JoinColumn(name = "hourId")
)
private List<Hour> hours = new ArrayList<>();
public User() {
}
public User(String username, String password, String fullname, String email, String creation_date) {
this.username = username;
this.password = password;
this.fullname = fullname;
this.email = email;
this.roles = getRoles();
this.creation_date = creation_date;
}
//If user is admin
public boolean isAdmin() {
return roles.contains(Role.ADMIN);
}
//region Getters & Setters
public void setId(int id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setFullname(String fullName) {
this.fullname = fullName;
}
public void setEmail(String email) { this.email = email; }
public void setRoles(Set<Role> roles) { this.roles = roles; }
public void setCreation_date(String creation_date) { this.creation_date = creation_date; }
public int getId() { return id; }
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getFullname() {
return fullname;
}
public String getEmail() { return email; }
public Set<Role> getRoles() { return roles; }
public String getCreation_date() { return creation_date; }
//endregion
}
UserHour Entity:
package com.timely.backend.models;
import javax.persistence.*;
#Entity
#Table(name = "user_hour")
public class UserHour {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getHourId() {
return hourId;
}
public void setHourId(int hourId) {
this.hourId = hourId;
}
public UserHour(int userId, int hourId) {
this.userId = userId;
this.hourId = hourId;
}
public UserHour(){
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int userId;
private int hourId;
}
Hour Entity:
package com.timely.backend.models;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "HOUR")
public class Hour {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int hourId;
private String date;
private String startTime;
private String endTime;
public Hour(int hourId, String date, String startTime, String endTime) {
this.hourId = hourId;
this.date = date;
this.startTime = startTime;
this.endTime = endTime;
}
public Hour(){
}
#ManyToMany(mappedBy = "hours")
private List<User> users = new ArrayList<>();
public int gethourId() {
return hourId;
}
public void sethourId(int hourId) {
this.hourId = hourId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
}
MySQL query working:
SELECT id, date, start_time, end_time FROM hour
JOIN user_hour
ON user_hour.hour_id = hour.hour_id
WHERE user_hour.user_id = '1'
Problem:
User Table:
UserHour Table:
Hour Table:

Related

joining multiple entities in Spring JPA

Have Users, Roles and User Roles tables.
Users
id
username
Roles
role_id
role_name
user_roles
user_id (fk users table)
role_id (fk roles table)
I defined my entities this way
user_roles Entity
#Column(name = "USER_ID")
private int userId;
#Column(name = "ROLE_ID")
private int roleId;
#ManyToOne()
#JoinColumn(name="ROLE_ID", insertable = false, updatable = false)
private RoleGroup userRole;
#ManyToOne()
#JoinColumn(name="id", insertable = false, updatable = false)
private User user;
User entity:
#Id
#Column(name="ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "USER_NAME")
private String userName;
Roles Entity:
#Id
#Column(name="ROLE_ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "ROLE_NAME")
private String roleName;
#OneToMany(targetEntity=UserRoleGroup.class, mappedBy="userRole",cascade=CascadeType.ALL,
fetch = FetchType.LAZY)
private List<UserRoleGroup> userGroup;
User table will store all lists of users. Roles table is the master table which is having 5 rows - (Admin, Read, manager..)
User Role Table will have user_id from user table and role_id from roles table.
Example
USER:
id user_name
1 test#gmail.com
2 abc#gmail.com
Roles
role_id Name
1 Admin
2 Manager
3 Read
User Roles
User_Id Role_ID
1 1
1 2
2 3
Repository
#Query("FROM UserRoleGroup AS urg LEFT JOIN urg.userRole AS ur LEFT JOIN urg.user AS u WHERE u.userName = ?1")
public List<UserRoleGroup> findAllUserRoles(String userName);
No compilation error, no runtime error, but query isn't returning anything whereas I have data in table. when i run query in MySql I am getting data
I was able to get this working with some minor changes to the entity classes and by adding a DTO. I think its not a good practice to pass around the entity to the client. Below is my implementation.
UserRoleGroup
#Entity
#Table#Data
public class UserRoleGroup {
#EmbeddedId
private UserRoleId id;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("userId")
private User user;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("roleId")
private Role role;
}
UserRoleId
#Embeddable
public static class UserRoleId implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "user_id")
private Integer userId;
#Column(name = "role_id")
private Integer roleId;
public UserRoleId() {
}
public UserRoleId(Integer userId, Integer roleId) {
super();
this.userId = userId;
this.roleId = roleId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserRoleId that = (UserRoleId) o;
if (!userId.equals(that.userId)) return false;
return roleId.equals(that.roleId);
}
#Override
public int hashCode() {
int result = userId.hashCode();
result = 31 * result + roleId.hashCode();
return result;
}
}
User
import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* user can have roles
* */
#Entity
#Table
public class User {
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "username")
private String userName;
#OneToMany(mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true)
private Set<UserRoleGroup> roles = new HashSet<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Set<UserRoleGroup> getRoles() {
return roles;
}
public void setRoles(Set<UserRoleGroup> roles) {
this.roles = roles;
}
}
Role
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "roles")
public class Role {
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "role_name")
private String roleName;
#OneToMany(mappedBy="role",
cascade=CascadeType.ALL,
fetch = FetchType.LAZY)
private List<UserRoleGroup> users = new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<UserRoleGroup> getUsers() {
return users;
}
public void setUsers(List<UserRoleGroup> users) {
this.users = users;
}
}
UserGroupRepository
import com.chait.json.generate.entity.UserRoleGroup;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface UserGroupRepository extends JpaRepository<UserRoleGroup,Integer> {
#Query(
"FROM UserRoleGroup AS urg LEFT JOIN urg.role AS ur LEFT JOIN urg.user AS u WHERE u.userName = ?1"
)
List<UserRoleGroup> findAllUserRoles(#Param("userName") String userName);
}
UserRoleDTO
#Data
#AllArgsConstructor
public class UserRoleDTO {
private String username;
private Set<String> roles;
}
UserRestController
#RestController
#RequestMapping("/users")
#RequiredArgsConstructor
public class UserRestController {
private final UserGroupRepository userGroupRepository;
#GetMapping("/{username}")
public ResponseEntity<UserRoleDTO> getUserRoleByUsername(
#PathVariable("username") String username
) {
List<UserRoleGroup> userRoleGroups = userGroupRepository.findAllUserRoles(username);
return ResponseEntity.ok(
new UserRoleDTO(
userRoleGroups.get(0).getUser().getUserName(),
userRoleGroups
.stream()
.map(UserRoleGroup::getRole)
.map(Role::getRoleName)
.collect(Collectors.toSet())
)
);
}
}

When insert values to composite table (Join table), it makes other two table values as null Spring JPA

Books Class
#Component
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
#Entity
#Table(name = "books")
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "bookId", scope = Books.class)
public class Books {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "bookId")
private Long bookId;
#Column(unique = true)
private String book_reference;
private String isbn;
private String title;
private String author;
private String publication;
private String edition;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private Date published_year;
private String category;
private int number_of_copies;
#OneToMany(mappedBy = "books", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<IssuedBooks> issuedBooks;
public Books(String book_reference, String isbn, String title, String author, String publication, String edition, Date published_year, String category, int number_of_copies) {
this.book_reference = book_reference;
this.isbn = isbn;
this.title = title;
this.author = author;
this.publication = publication;
this.edition = edition;
this.published_year = published_year;
this.category = category;
this.number_of_copies = number_of_copies;
}
}
Student Class
#Component
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
#Entity
#Table(name = "students")
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "studentId", scope = Students.class)
public class Students {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "studentId")
private Long studentId;
private String first_name;
private String last_name;
#Column(unique = true)
private String email;
private String address;
private String telephone;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private Date registered_date;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private Date terminated_date;
#OneToMany(mappedBy = "students", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<IssuedBooks> issuedBooks;
public Students(String first_name, String last_name, String email, String address, String telephone, Date registered_date, Date terminated_date) {
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
this.address = address;
this.telephone = telephone;
this.registered_date = registered_date;
this.terminated_date = terminated_date;
}
}
Join Table Classes
I have join two entity Students and Books
IssuedBooksId Class
#Embeddable
public class IssuedBooksId implements Serializable {
#Column(name = "bookId")
private Long bookId;
#Column(name = "studentId")
private Long studentId;
public IssuedBooksId() {
}
public IssuedBooksId(Long bookId, Long studentId) {
this.bookId = bookId;
this.studentId = studentId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IssuedBooksId that = (IssuedBooksId) o;
return bookId.equals(that.bookId) &&
studentId.equals(that.studentId);
}
#Override
public int hashCode() {
return Objects.hash(bookId, studentId);
}
}
IssuedBooks Class /
#Data
#Entity
#Table(name = "issuedBooks")
#JsonIdentityInfo(scope = IssuedBooks.class,
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "issuedBooksId")
public class IssuedBooks {
#EmbeddedId
private IssuedBooksId issuedBooksId = new IssuedBooksId();
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#MapsId("bookId")
#JoinColumn(name = "bookId")
private Books books;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#MapsId("studentId")
#JoinColumn(name = "studentId")
private Students students;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private Date issueDate;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private Date returnDate;
public IssuedBooks() {
}
public IssuedBooks(Books books, Students students) {
this.books = books;
this.students = students;
this.issuedBooksId = new IssuedBooksId(books.getBookId(), students.getStudentId());
}
public IssuedBooks(Books books, Students students, Date issueDate, Date returnDate) {
this.books = books;
this.students = students;
this.issuedBooksId = new IssuedBooksId(books.getBookId(), students.getStudentId());
this.issueDate = issueDate;
this.returnDate = returnDate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IssuedBooks that = (IssuedBooks) o;
return books.equals(that.books) &&
students.equals(that.students);
}
#Override
public int hashCode() {
return Objects.hash(books, students);
}
}
I tried #JsonIdentityInfo as belows
ObjectIdGenerators.IntSequenceGenerator.class ObjectIdGenerators.PropertyGenerator ObjectIdGenerators.UUIDGenerator
After Inserting values to IssueBooks table other tables like this
Books Table
Student Table
IssueBooks Table
I resolved this problem.
The solution is; should make child class cascadeType as Persist
#EmbeddedId
IssueBooksId issueBooksId = new IssueBooksId();
#ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
#MapsId("bookId")
#JoinColumn(name = "bookId")
private Books books;
#ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
#MapsId("studentId")
#JoinColumn(name = "studentId")
private Students students;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private Date issueDate;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private Date returnDate;

The boolean value of the objects coming from a Query is wrong

I have this activity_company table which includes an activity and company. I am trying to order the result of this query by modified_date and id. And in the activity table there is a boolean field such as shared. All the shared values are false in the database but after this query the resulted objects' shared fields are displayed as true even if they are still false in the DB. Any idea what causes this situation ?
SELECT activity.*
FROM activity
INNER JOIN activity_company ON activity.id=activity_company.activity_id
WHERE activity_company.company_id=1
ORDER BY activity.modified_date, activity.id
This is the activity class;
#Entity
public class Activity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(columnDefinition = "TEXT")
private String param;
private Date createdDate;
private int activityType;
private long classNameId;
private long classPK;
private Date modifiedDate;
private boolean shared;
#ManyToOne
private User creatorUser;
#ManyToOne
private Company creatorCompany;
#OneToMany(mappedBy = "activity")
private List<ActivityCompany> activityCompanies = new ArrayList<ActivityCompany>();
#OneToMany(mappedBy = "activity")
private List<ActivityAttachment> activityAttachments;
public Activity(String param, User user, int activityType) {
this.param = param;
this.createdDate = new Date();
this.activityType = activityType;
this.creatorUser = user;
this.modifiedDate = new Date();
}
and activitycompany;
#Entity
public class ActivityCompany {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
private Activity activity;
#ManyToOne
private Company company;
public Activity getActivity() {
return activity;
}
public void setActivity(Activity activity) {
this.activity = activity;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public Long getId() {
return id;
}
}

how to write this query using hql

Thi is my query:
SELECT d.fullName,d.doctorId,d.speciality, t.hospital, t.date, t.time
FROM Doctor d, TimeTable t
WHERE d.doctorId = t.doctorId and d.fullName = 'Subash Nisam' and t.date = '2017.03.02'
ORDER BY t.date;
I've two tables->Doctor and TimeTable
#Entity
public class TimeTable {
private int timeTableId;
private String time;
private String date;
private String hospital;
private Doctor doctor;
#Id
#GeneratedValue(strategy = AUTO)
public int getTimeTableId() {
return timeTableId;
}
public void setTimeTableId(int timeTableId) {
this.timeTableId = timeTableId;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getHospital() {
return hospital;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "doctorId", nullable = false)
public Doctor getDoctor() {
return doctor;
}
public void setDoctor(Doctor doctor) {
this.doctor = doctor;
}
}
//////////////////////////////////////////
#Entity
public class Doctor {
private int doctorId;
private String fullName;
private String regNo;
private String designation;
private String speciality;
private String address;
private String contactNo;
private String email;
private String workingTime;
private String password;
private String branch;
---------------------------------------------
#Id
#GeneratedValue(strategy = AUTO)
public int getDoctorId() {
return doctorId;
}
#OneToMany(cascade = CascadeType.ALL, mappedBy = "doctor")
public Set<TimeTable> getTimeTables() {
return timeTables;
}
public void setTimeTables(Set<TimeTable> timeTables) {
this.timeTables = timeTables;
}
}
I want to write my query using hql. hope your help.
Try this syntax:
select d.fullName, d.doctorId, d.speciality, t.hospital, t.date, t.time
from Doctor as d
inner join d.timeTables t
where d.fullName = 'Subash Nisam' and t.date = '2017-03-02'
Try this one
select Doctor.fullname, Doctor.doctorId, Doctor.speciality, TimeTable.hospital, TimeTable.date, TimeTable.time from Doctor inner join TimeTable on Doctor.doctorId =TimeTable.doctorId where Doctor.fullname='Subash' and Timetable.date='2017-03-02' order by Timetable.date;
#Tim Biegeleisen------->
Here is the output
select
doctor0_.doctorId as doctorId1_3_0_,
timetables1_.timeTableId as timeTabl1_5_1_,
doctor0_.address as address2_3_0_,
doctor0_.branch as branch3_3_0_,
doctor0_.contactNo as contactN4_3_0_,
doctor0_.designation as designat5_3_0_,
doctor0_.email as email6_3_0_,
doctor0_.fullName as fullName7_3_0_,
doctor0_.password as password8_3_0_,
doctor0_.regNo as regNo9_3_0_,
doctor0_.speciality as special10_3_0_,
doctor0_.workingTime as working11_3_0_,
timetables1_.date as date2_5_1_,
timetables1_.doctorId as doctorId5_5_1_,
timetables1_.hospital as hospital3_5_1_,
timetables1_.time as time4_5_1_
from
Doctor doctor0_
inner join
TimeTable timetables1_
on doctor0_.doctorId=timetables1_.doctorId
where
doctor0_.fullName='Subash Nisam'
and timetables1_.date='2017.03.02'
It gives all result of the doctor such as fullname, password, address...
but I want to get fullName and doctorId from doctor table and other data from timetable table.

#EmbeddedId throws IdIdentifierGenerationException: null id generated even with #GeneratedValue(strategy = GenerationType.AUTO)

Hi my relation throws #EmbeddedId throws IdIdentifierGenerationException: null id. Any advices is welcome. Here is my Code:
TABLE ACTIVIDADES(
CODIGO CHAR(10) NOT NULL UNIQUE,
NOMBRE VARCHAR(50) UNIQUE,
PRIMARY KEY(CODIGO)
)ENGINE=INNODB;
CREATE TABLE EVENTOS_ACTIVIDADES(
ID INT AUTO_INCREMENT,
CODIGO_ACTIVIDADES CHAR(10) NOT NULL UNIQUE,
PRIMARY KEY(ID,CODIGO_ACTIVIDADES),
FOREIGN KEY(CODIGO_ACTIVIDADES) REFERENCES ACTIVIDADES(CODIGO) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=INNODB;
Here are my JPA Entities:
#Entity
#Table(name = "eventos_actividades", catalog = "capacitacion_csg", uniqueConstraints = #UniqueConstraint(columnNames = "CODIGO_ACTIVIDADES"))
public class EventosActividades implements java.io.Serializable {
private EventosActividadesId id;
private Actividades actividades;
public EventosActividades() {
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "id", column = #Column(name = "ID", nullable = false)),
#AttributeOverride(name = "codigoActividades", column = #Column(name = "CODIGO_ACTIVIDADES", unique = true, nullable = false, length = 10)) })
public EventosActividadesId getId() {
return this.id;
}
public void setId(EventosActividadesId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "CODIGO_ACTIVIDADES", unique = true, nullable = false, insertable = false, updatable = false)
public Actividades getActividades() {
return this.actividades;
}
public void setActividades(Actividades actividades) {
this.actividades = actividades;
}
#Entity
#Table(name="ACTIVIDADES", catalog="CAPACITACION_CSG", uniqueConstraints = {#UniqueConstraint(columnNames="NOMBRE"), #UniqueConstraint(columnNames="CODIGO")})
public class Actividades {
private String codigo;
private String nombre;
private List<EventosActividades> eventosActividades;
#Column(name="NOMBRE",unique=true,nullable=false,length=50)
public String getNombre() {
return nombre;
}
#Id
#Column(name="CODIGO",unique=true,nullable=false,length=10)
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
#OneToMany(fetch= FetchType.EAGER,mappedBy="actividades",cascade=CascadeType.ALL)
public List<EventosActividades> getEventosActividades() {
return eventosActividades;
}
public void setEventosActividades(List<EventosActividades> eventosActividades) {
this.eventosActividades = eventosActividades;
}
}
#Embeddable
public class EventosActividadesId implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String codigoActividades;
public EventosActividadesId() {
}
public EventosActividadesId(int id, String codigoActividades) {
this.id = id;
this.codigoActividades = codigoActividades;
}
#Column(name = "ID", nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "CODIGO_ACTIVIDADES", unique = true, nullable = false, length = 10)
public String getCodigoActividades() {
return this.codigoActividades;
}
public void setCodigoActividades(String codigoActividades) {
this.codigoActividades = codigoActividades;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof EventosActividadesId))
return false;
EventosActividadesId castOther = (EventosActividadesId) other;
return (this.getId() == castOther.getId())
&& ((this.getCodigoActividades() == castOther
.getCodigoActividades()) || (this
.getCodigoActividades() != null
&& castOther.getCodigoActividades() != null && this
.getCodigoActividades().equals(
castOther.getCodigoActividades())));
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getId();
result = 37
* result
+ (getCodigoActividades() == null ? 0 : this
.getCodigoActividades().hashCode());
return result;
}
}
THANKS for everyone, I've not initialize my #Embeddable EventosActividadesId class and set in my EventosActividades Entity like this way:
EventosActividadesId id = new EventosActividadesId();
id.setCodigoActividades("ACTCBK");
eventosActividades.setId(id);