I have a ShippingDestination entity that I only want a new one saved if it doesn't already exist. It must match exactly.
Will Hibernate or Spring be able to help with this, or is this portion all up to me?
#javax.persistence.Table(name = "Shipping_Destination", schema = "", catalog = "production_queue")
#Entity
public class ShippingDestination {
private Integer id;
#javax.persistence.Column(name = "id", nullable = false, insertable = true, updatable = true, length = 10, precision = 0)
#Id
#GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
private String recipient;
#javax.persistence.Column(name = "recipient", nullable = false, insertable = true, updatable = true, length = 32, precision = 0)
#Basic
public String getRecipient() {
return recipient;
}
#JsonProperty("Recipient")
public void setRecipient(String recipient) {
this.recipient = recipient;
}
private String street;
#javax.persistence.Column(name = "street", nullable = false, insertable = true, updatable = true, length = 255, precision = 0)
#Basic
public String getStreet() {
return street;
}
#JsonProperty("Street")
public void setStreet(String street) {
this.street = street;
}
private String street2;
#javax.persistence.Column(name = "street2", nullable = false, insertable = true, updatable = true, length = 255, precision = 0)
#Basic
public String getStreet2() {
return street2;
}
#JsonProperty("Street2")
public void setStreet2(String street2) {
this.street2 = street2;
}
private String city;
#javax.persistence.Column(name = "city", nullable = false, insertable = true, updatable = true, length = 128, precision = 0)
#Basic
public String getCity() {
return city;
}
#JsonProperty("City")
public void setCity(String city) {
this.city = city;
}
private String state;
#javax.persistence.Column(name = "state", nullable = false, insertable = true, updatable = true, length = 2, precision = 0)
#Basic
public String getState() {
return state;
}
#JsonProperty("State")
public void setState(String state) {
this.state = state;
}
private String postalCode;
#javax.persistence.Column(name = "postal_code", nullable = false, insertable = true, updatable = true, length = 12, precision = 0)
#Basic
public String getPostalCode() {
return postalCode;
}
#JsonProperty("PostalCode")
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ShippingDestination that = (ShippingDestination) o;
if (city != null ? !city.equals(that.city) : that.city != null) return false;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (postalCode != null ? !postalCode.equals(that.postalCode) : that.postalCode != null) return false;
if (recipient != null ? !recipient.equals(that.recipient) : that.recipient != null) return false;
if (state != null ? !state.equals(that.state) : that.state != null) return false;
if (street != null ? !street.equals(that.street) : that.street != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (recipient != null ? recipient.hashCode() : 0);
result = 31 * result + (street != null ? street.hashCode() : 0);
result = 31 * result + (city != null ? city.hashCode() : 0);
result = 31 * result + (state != null ? state.hashCode() : 0);
result = 31 * result + (postalCode != null ? postalCode.hashCode() : 0);
return result;
}
private Collection<Order> orders;
#OneToMany(mappedBy = "shippingDestination")
public Collection<Order> getOrders() {
return orders;
}
public void setOrders(Collection<Order> orders) {
this.orders = orders;
}
private Collection<Vendor> vendors;
#OneToMany(mappedBy = "shippingDestination")
public Collection<Vendor> getVendors() {
return vendors;
}
public void setVendors(Collection<Vendor> vendors) {
this.vendors = vendors;
}
public boolean validate() throws InvalidParameterException {
if (getRecipient() == null || getRecipient().length() == 0) {
throw new InvalidParameterException("Address requires a recipient");
}
if (getStreet() == null || getStreet().length() == 0) {
throw new InvalidParameterException("Address requires a street");
}
if (getCity() == null || getCity().length() == 0) {
throw new InvalidParameterException("Address requires a city");
}
if (getState() == null || getState().length() == 0) {
throw new InvalidParameterException("Address requires a state");
}
if (getPostalCode() == null || getPostalCode().length() == 0) {
throw new InvalidParameterException("Address requires a postal code");
}
return true;
}
}
yes, there is no such thing in spring or hibernate. If you need to check for duplicate i mean whether same information already exist or not then sure you can write a query in service or dao class.
Related
I have table
#Entity
#Table(name = "User", schema = "swprojekt", catalog = "")
public class UserEntity {
private String password;
private String email;
private int userId;
private String firstName;
private String lastName;
private String addressHouseNumber;
private String addressStreet;
private String addressCity;
private String addressState;
private String phoneNumber;
private int isAdmin;
#Basic
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Basic
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Id
#Column(name = "user_id")
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
#Basic
#Column(name = "first_name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Basic
#Column(name = "last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Basic
#Column(name = "address_house_number")
public String getAddressHouseNumber() {
return addressHouseNumber;
}
public void setAddressHouseNumber(String addressHouseNumber) {
this.addressHouseNumber = addressHouseNumber;
}
#Basic
#Column(name = "address_street")
public String getAddressStreet() {
return addressStreet;
}
public void setAddressStreet(String addressStreet) {
this.addressStreet = addressStreet;
}
#Basic
#Column(name = "address_city")
public String getAddressCity() {
return addressCity;
}
public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
#Basic
#Column(name = "address_state")
public String getAddressState() {
return addressState;
}
public void setAddressState(String addressState) {
this.addressState = addressState;
}
#Basic
#Column(name = "phone_number")
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Basic
#Column(name = "is_admin")
public int getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(int isAdmin) {
this.isAdmin = isAdmin;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserEntity that = (UserEntity) o;
if (userId != that.userId) return false;
if (isAdmin != that.isAdmin) return false;
if (password != null ? !password.equals(that.password) : that.password != null) return false;
if (email != null ? !email.equals(that.email) : that.email != null) return false;
if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) return false;
if (lastName != null ? !lastName.equals(that.lastName) : that.lastName != null) return false;
if (addressHouseNumber != null ? !addressHouseNumber.equals(that.addressHouseNumber) : that.addressHouseNumber != null)
return false;
if (addressStreet != null ? !addressStreet.equals(that.addressStreet) : that.addressStreet != null) return false;
if (addressCity != null ? !addressCity.equals(that.addressCity) : that.addressCity != null) return false;
if (addressState != null ? !addressState.equals(that.addressState) : that.addressState != null) return false;
if (phoneNumber != null ? !phoneNumber.equals(that.phoneNumber) : that.phoneNumber != null) return false;
return true;
}
#Override
public int hashCode() {
int result = password != null ? password.hashCode() : 0;
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + userId;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (addressHouseNumber != null ? addressHouseNumber.hashCode() : 0);
result = 31 * result + (addressStreet != null ? addressStreet.hashCode() : 0);
result = 31 * result + (addressCity != null ? addressCity.hashCode() : 0);
result = 31 * result + (addressState != null ? addressState.hashCode() : 0);
result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0);
result = 31 * result + isAdmin;
return result;
}
}
its called User.
I want to insert the data into it:
#Transactional
public boolean register( UserEntity u){
Query q = em.createNativeQuery("Select * from User where email = ?1", UserEntity.class);
q.setParameter(1, u.getEmail());
List<UserEntity> registeredUser = q.getResultList();
if( registeredUser.isEmpty()) {
try{
u.setPassword(BCrypt.hashpw(u.getPassword(), BCrypt.gensalt(16)));;
em.persist(u);
return true;
}catch( DataAccessException e ){
return false;
}
}
return false;
}
However this keep throwing exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'swprojekt.user' doesn't exist
i have read that it is case sensitive so i tried to rename
#Table(name = "User" ... ) to #Table( name = "user"...)
i have defined
spring.datasource.username = name
spring.datasource.password = password
in application.properties file.
Which did not help. Also when i try to access another table in database it works.
WHat may cause this exception?
Thanks for help.
#EntityScan only identifies which classes should be used by a specific persistence context.
Example:
#EntityScan(basePackages = {"com.project.model"}) // scan JPA entities
And
spring.jpa.hibernate.ddl-auto = create
Update :
If there are other tables, change the table name.
#Table(name = "User_Tbl")
do you have your properties over there??? because most probably the name of the database is not setting for example :
dbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sys //name of the database
jdbc.username=root
jdbc.password=asdadsadsadsa
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=false
hibernate.format_sql=false
example for mysql
I learn the hibernate framework and I am so confused with generated sql.
I have the following code:
Table:
CREATE TABLE users (
user_id int NOT NULL AUTO_INCREMENT,
login varchar(20) UNIQUE,
pass varchar(20),
user_name varchar(20),
surname varchar(20),
PRIMARY KEY (user_id)
)
Model:
#Entity
#Table(name="users", catalog="maximodb")
public class User implements Serializable{
#Id
#Column(name="user_id")
#GeneratedValue(strategy =GenerationType.IDENTITY)
private Integer userId;
#Column(name = "login", unique = true, length = 20)
private String login;
#Column(name = "pass", length = 20)
private String pass;
#Column(name = "user_name", length = 20)
private String userName;
#Column(name = "surname", length = 20)
private String surname;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "users_roles", joinColumns = { #JoinColumn(name = "user_id") }, inverseJoinColumns = { #JoinColumn(name = "role_id") })
private Set<Role> userRoles = new HashSet<Role>();
public User() {
}
public User(String login, String pass, String userName, String surname) {
this.login = login;
this.pass = pass;
this.userName = userName;
this.surname = surname;
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getLogin() {
return this.login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPass() {
return this.pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSurname() {
return this.surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Set<Role> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<Role> userRoles) {
this.userRoles = userRoles;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((login == null) ? 0 : login.hashCode());
result = prime * result + ((pass == null) ? 0 : pass.hashCode());
result = prime * result + ((surname == null) ? 0 : surname.hashCode());
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
result = prime * result + ((userRoles == null) ? 0 : userRoles.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (login == null) {
if (other.login != null)
return false;
} else if (!login.equals(other.login))
return false;
if (pass == null) {
if (other.pass != null)
return false;
} else if (!pass.equals(other.pass))
return false;
if (surname == null) {
if (other.surname != null)
return false;
} else if (!surname.equals(other.surname))
return false;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
if (userRoles == null) {
if (other.userRoles != null)
return false;
} else if (!userRoles.equals(other.userRoles))
return false;
return true;
}
}
And now... dao function (two variants):
The first:
List<User> users = new ArrayList<User>();
users = sessionFactory.getCurrentSession()
.createQuery("from User where login= :login")
.setString( "login", login )
.list();
if (users.size() > 0) {
return users.get(0);
} else {
return null;
}
Returned sql:
select
user0_.user_id as user_id1_1_,
user0_.login as login2_1_,
user0_.pass as pass3_1_,
user0_.surname as surname4_1_,
user0_.user_name as user_nam5_1_
from
maximodb.users user0_
where
user0_.login=?
And the second variant:
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(User.class);
List<User> a = (List<User>) criteria.list();
User us = a.get(0);
return us;
Returned sql:
select
this_.user_id as user_id1_1_0_,
this_.login as login2_1_0_,
this_.pass as pass3_1_0_,
this_.surname as surname4_1_0_,
this_.user_name as user_nam5_1_0_
from
maximodb.users this_
The second variant is quite correct and gets user from the db. But in the first case there is a null pointer exception instead of User object. What is incorrect?
It is worth to higilight that generated sql works good in MySql Workbench (first case).
The first variant try to get a user with the given login but no user found for this login (verify that there is a user with the given login in database).
The second variant list all users in the database and than get the first one. Your User table contain some users that's why this variant return a user and not null.
There are the entities Cookbook, Recipe. It's a ManyToMany relation: a cookbook can have multiple recipes and a recipe can be assigned to multiple cookbooks. So I added the entity CookbookRecipe and connected the entities as OneToMany.
Where to put a method to add/remove the relation between Cookbook and Recipe - does this method has to add a new CookbookRecipe and add this CookbookRecipe to Cookbook and Recipe?
In my understanding I would expect a
public void addRecipe(Recipe recipe) {
CookbookRecipe relation = new CookbookRecipe();
relation.setCookbook(this);
relation.setRecipe(recipe);
this.cookbookRecipes.add( relation );
}
Is this the right direction?
Would I add this method to the Cookbook DAO or Recipe DAO or put this into a service?
#Entity
public class Cookbook {
private Integer id;
private String title;
private Collection<CookbookRecipe> cookbookRecipes;
private Collection<CookbookSortlevel> cookbookSortlevels;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Basic
#Column(name = "title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cookbook cookbook = (Cookbook) o;
if (id != null ? !id.equals(cookbook.id) : cookbook.id != null) return false;
if (title != null ? !title.equals(cookbook.title) : cookbook.title != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
return result;
}
#OneToMany(mappedBy = "cookbook", fetch = FetchType.EAGER)
public Collection<CookbookRecipe> getCookbookRecipes() {
return cookbookRecipes;
}
public void setCookbookRecipes(Collection<CookbookRecipe> cookbookRecipes) {
this.cookbookRecipes = cookbookRecipes;
}
#OneToMany(mappedBy = "cookbook")
public Collection<CookbookSortlevel> getCookbookSortlevels() {
return cookbookSortlevels;
}
public void setCookbookSortlevels(Collection<CookbookSortlevel> cookbookSortlevels) {
this.cookbookSortlevels = cookbookSortlevels;
}
}
#Entity
#Table(name = "cookbook_recipe", schema = "", catalog = "")
public class CookbookRecipe {
private Integer id;
private Recipe recipe;
private Cookbook cookbook;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CookbookRecipe that = (CookbookRecipe) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
return result;
}
#ManyToOne
#JoinColumn(name = "recipe_id", referencedColumnName = "id")
public Recipe getRecipe() {
return recipe;
}
public void setRecipe(Recipe recipe) {
this.recipe = recipe;
}
#ManyToOne
#JoinColumn(name = "cookbook_id", referencedColumnName = "id", nullable=false,insertable=false,updatable=false )
public Cookbook getCookbook() {
return cookbook;
}
public void setCookbook(Cookbook cookbook) {
this.cookbook = cookbook;
}
}
#Entity
public class Recipe {
private Integer id;
private String title;
private String text;
private Collection<RecipeIngredient> recipeIngredients;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Basic
#Column(name = "title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Basic
#Column(name = "text")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Recipe recipe = (Recipe) o;
if (id != null ? !id.equals(recipe.id) : recipe.id != null) return false;
if (title != null ? !title.equals(recipe.title) : recipe.title != null) return false;
if (text != null ? !text.equals(recipe.text) : recipe.text != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (text != null ? text.hashCode() : 0);
return result;
}
#OneToMany(mappedBy = "recipe")
public Collection<RecipeIngredient> getRecipeIngredients() {
return recipeIngredients;
}
public void setRecipeIngredients(Collection<RecipeIngredient> recipeIngredients) {
this.recipeIngredients = recipeIngredients;
}
}
Are there any github projects handling this you could suggest?
This is, for me, the right direction. The code looks good
I think you should add it in the CookBookDAO because the Cookbook contains Recipes not the opposite
I have following classes in my project.
Employee class
#XmlRootElement
#Entity
#Table(name = "emp", catalog = "emps")
public class Employee implements java.io.Serializable {
//other entity variables
private Set<Title> titles = new HashSet<Title>(0);
#XmlTransient
#OneToMany(targetEntity = Title.class, fetch = FetchType.EAGER, mappedBy = "employee", cascade=CascadeType.ALL)
public Set<Title> getTitles() {
return this.titles;
}
public void setTitles(Set<Title> titles) {
this.titles = titles;
}
}
Title
#Entity
#Table(name = "titles", catalog = "emps")
public class Title implements java.io.Serializable {
private TitleId id;
private Employee employee;
private Date fromDate;
private Date toDate;
public Title() {
}
public Title(TitleId id, Employee employee) {
this.id = id;
this.employee = employee;
}
public Title(TitleId id, Employee employee, Date toDate) {
this.id = id;
this.employee = employee;
this.toDate = toDate;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "empNo", column = #Column(name = "emp_no", nullable = false)),
#AttributeOverride(name = "title", column = #Column(name = "title", nullable = false, length = 50)),
#AttributeOverride(name = "fromDate", column = #Column(name = "from_date", nullable = false, length = 10)) })
public TitleId getId() {
return this.id;
}
public void setId(TitleId id) {
this.id = id;
}
//rest of the code
}
Title Id
#Embeddable
public class TitleId implements java.io.Serializable {
private int empNo;
private String title;
private Date fromDate;
public TitleId() {
}
public TitleId(int empNo, String title, Date fromDate) {
this.empNo = empNo;
this.title = title;
this.fromDate = fromDate;
}
#Column(name = "emp_no", nullable = false)
public int getEmpNo() {
return this.empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
#Column(name = "title", nullable = false, length = 50)
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "from_date", nullable = false, length = 10)
public Date getFromDate() {
return this.fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof TitleId))
return false;
TitleId castOther = (TitleId) other;
return (this.getEmpNo() == castOther.getEmpNo())
&& ((this.getTitle() == castOther.getTitle()) || (this
.getTitle() != null && castOther.getTitle() != null && this
.getTitle().equals(castOther.getTitle())))
&& ((this.getFromDate() == castOther.getFromDate()) || (this
.getFromDate() != null
&& castOther.getFromDate() != null && this
.getFromDate().equals(castOther.getFromDate())));
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getEmpNo();
result = 37 * result
+ (getTitle() == null ? 0 : this.getTitle().hashCode());
result = 37 * result
+ (getFromDate() == null ? 0 : this.getFromDate().hashCode());
return result;
}
}
I need to create a criteria to find the first name, last name and title of the users. The first name and last names are working fine in my criteria. The following code shows how I create my criteria for titles. "jobTitle" is a parameter that I'm passing to it.
Criteria employeeSearchCriteria = getSession().createCriteria(Employee.class);
employeeSearchCriteria.setFirstResult(0);
employeeSearchCriteria.setMaxResults(6);
employeeSearchCriteria.createAlias("titles.TitleId", "titleId");
employeeSearchCriteria.add(Restrictions.eq("titleId.title", jobTitle));
When I run the code it throws an Query Exception saying org.hibernate.QueryException: could not resolve property: TitleId of: Title. Can anyone help me in this matter?
I'm guessing here, but try changing in class Title the getter method name from getId() to getTitleId().
Otherwise, I can just say that all of the examples I saw that uses #EmbeddedId show how to do it on the field itself, rather than on the getter as you did. So you might just as well try also to annotate the field (although Hibernate recommends not to mix method and field mapping annotations).
Supposing I have entity Lecturer and Course two entities having many to many relationships in JPA 2.0
It is perfectly OK to have a non-annotated entity LecturerCourse (with multi-table selection columns, not annotated) and JPQL like this working.
final Query query = em.createQuery(
"select new com.cs.entity.LectureCourse(l.id, l.name, l.surName, " +
"l.type, c.code, c.name) from lecturer l join l.courses c where l.id = :l_id"
);
How can I do the same with JPA Criteria API?
Here are the code for Lecturer and Courses respectively
#Entity(name = "course")
public class Course implements Serializable {
#Id
#Column(name = "course_code", columnDefinition = "char(6)",
unique = true, nullable = false)
private String code;
#Column(name = "course_name")
private String name;
#ManyToMany(mappedBy = "courseSet", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Student> students;
#ManyToOne(fetch = FetchType.EAGER, targetEntity = Lecturer.class)
#JoinColumn(name = "lecture_id")
private Lecturer lecturer;
public Course() {
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
public Lecturer getLecturer() {
return lecturer;
}
public void setLecturer(Lecturer lecturer) {
this.lecturer = lecturer;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Course)) return false;
Course course = (Course) o;
if (code != null ? !code.equals(course.code) : course.code != null) return false;
if (name != null ? !name.equals(course.name) : course.name != null) return false;
if (students != null ? !students.equals(course.students) : course.students != null) return false;
return true;
}
#Override
public int hashCode() {
int result = code != null ? code.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (students != null ? students.hashCode() : 0);
return result;
}
}
#Entity(name = "lecturer")
public class Lecturer {
public static enum LectureType{
FULL_TIME, PART_TIME
}
#Id
#Column(name = "lecture_id", nullable = false,
unique = true, columnDefinition = "char(8)")
private String id;
#Column(name = "lecture_name", length = 20, nullable = false)
private String name;
#Column(name = "lecture_sur_name", length = 20, nullable = false)
private String surName;
#Enumerated(EnumType.ORDINAL)
#Column(name = "lecture_type", columnDefinition = "char(1)")
private LectureType type;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "lecturer", fetch = FetchType.EAGER)
private Set<Course> courses;
public Lecturer() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public LectureType getType() {
return type;
}
public void setType(LectureType type) {
this.type = type;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
for(final Course course : this.courses){
course.setLecturer(this);
}
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Lecturer)) return false;
Lecturer lecturer = (Lecturer) o;
if (id != null ? !id.equals(lecturer.id) : lecturer.id != null) return false;
if (name != null ? !name.equals(lecturer.name) : lecturer.name != null) return false;
if (surName != null ? !surName.equals(lecturer.surName) : lecturer.surName != null) return false;
if (type != lecturer.type) return false;
return true;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (surName != null ? surName.hashCode() : 0);
result = 31 * result + (type != null ? type.hashCode() : 0);
return result;
}
}
What you're looking for is a form of CriteriaQuery#multiselect ... I'm assuming you're generating an appropriate static metamodel (that's where the EntityClass_.field pieces come from) but working by hand I come up with something like:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<LectureCourse> criteria = builder.createQuery(LectureCourse.class);
Root<Lecturer> l = criteria.from(Lecturer.class);
Path<Course> c = l.join(Lecturer_.courses);
ParameterExpression<String> l_id = builder.parameter(String.class);
Predicate lecturerIdMatches = builder.equal(l.get(Lecturer_.id),l_id);
TypedQuery<LectureCourse> query = em.createQuery(criteria.multiselect(l.get(Lecturer_.id), l.get(Lecturer_.name), l.get(Lecturer_.surName), l.get(Lecturer_.type), c.get(Course_.code), c.get(Course_.name)).where(lecturerIdMatches));
query.setParameter(l_id,"queryvalue");
List<LectureCourse> results = query.getResultList();