Table xyz does not exist using JPA and spring - java

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

Related

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'crudRepository'

I work with a Spring boot project and I have the following entity class provided,
#Entity
public class User {
// form:hidden - hidden value
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
// form:input - textbox
#Column(name = "name", columnDefinition = "VARCHAR(30)", nullable = false)
String name;
// form:input - textbox
#Column(name = "email", columnDefinition = "VARCHAR(50)", nullable = false)
String email;
// form:textarea - textarea
#Column(name = "address", columnDefinition = "VARCHAR(255)", nullable = true)
String address;
// form:input - password
#Column(name = "password", columnDefinition = "VARCHAR(20)", nullable = false)
String password;
// form:input - password
String confirmPassword;
// form:checkbox - single checkbox
#Column(name = "newsletter", nullable = true)
boolean newsletter;
// form:checkboxes - multiple checkboxes
// #Column(columnDefinition = "VARCHAR(500)", nullable = false)
#ElementCollection
List<String> framework;
// form:radiobutton - radio button
#Column(name = "sex", columnDefinition = "VARCHAR(1)", nullable = true)
String sex;
// form:radiobuttons - radio button
#Column(name = "number", nullable = true)
Integer number;
// form:select - form:option - dropdown - single select
#Column(name = "", columnDefinition = "VARCHAR(10)", nullable = true)
String country;
// form:select - multiple=true - dropdown - multiple select
// #Column(columnDefinition = "VARCHAR(500)", nullable = true)
#ElementCollection
List<String> skill;
//Check if this is for New of Update
public boolean isNew() {
return (this.id == null);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public boolean isNewsletter() {
return newsletter;
}
public void setNewsletter(boolean newsletter) {
this.newsletter = newsletter;
}
public List<String> getFramework() {
return framework;
}
public void setFramework(List<String> framework) {
this.framework = framework;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public List<String> getSkill() {
return skill;
}
public void setSkill(List<String> skill) {
this.skill = skill;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
if (isNewsletter() != user.isNewsletter()) return false;
if (!getId().equals(user.getId())) return false;
if (!getName().equals(user.getName())) return false;
if (!getEmail().equals(user.getEmail())) return false;
if (getAddress() != null ? !getAddress().equals(user.getAddress()) : user.getAddress() != null) return false;
if (!getPassword().equals(user.getPassword())) return false;
if (getConfirmPassword() != null ? !getConfirmPassword().equals(user.getConfirmPassword()) : user.getConfirmPassword() != null)
return false;
if (!getFramework().equals(user.getFramework())) return false;
if (getSex() != null ? !getSex().equals(user.getSex()) : user.getSex() != null) return false;
if (getNumber() != null ? !getNumber().equals(user.getNumber()) : user.getNumber() != null) return false;
if (getCountry() != null ? !getCountry().equals(user.getCountry()) : user.getCountry() != null) return false;
return getSkill() != null ? getSkill().equals(user.getSkill()) : user.getSkill() == null;
}
#Override
public int hashCode() {
int result = getId().hashCode();
result = 31 * result + getName().hashCode();
result = 31 * result + getEmail().hashCode();
result = 31 * result + (getAddress() != null ? getAddress().hashCode() : 0);
result = 31 * result + getPassword().hashCode();
result = 31 * result + (getConfirmPassword() != null ? getConfirmPassword().hashCode() : 0);
result = 31 * result + (isNewsletter() ? 1 : 0);
result = 31 * result + getFramework().hashCode();
result = 31 * result + (getSex() != null ? getSex().hashCode() : 0);
result = 31 * result + (getNumber() != null ? getNumber().hashCode() : 0);
result = 31 * result + (getCountry() != null ? getCountry().hashCode() : 0);
result = 31 * result + (getSkill() != null ? getSkill().hashCode() : 0);
return result;
}
}
I would like to write some customized operations and tried to define the interfaces in that respect. The repository interfaces are provided below,
public interface CrudRepository<T, ID extends Serializable>
extends Repository<T, ID> {
<S extends T> S save(S entity);
T findOne(ID primaryKey);
Iterable<T> findAll();
Long count();
void delete(T entity);
boolean exists(ID primaryKey);
// … more functionality omitted.
}
This interface extends the previously provided interface,
#Repository
public interface IUserRepository extends CrudRepository<User, Long>{
}
While I compile the program, I get the following error,
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'crudRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object
What is the issue here?
Updated
The Spring Boot Application class is,
#SpringBootApplication
public class WebApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(WebApplication.class, args);
}
}
Add #NoRepositoryBean to your CrudRepository. This will allow auto-configuration to still occur without having to manually set the component scanning base packages.
The interface org.springframework.data.repository.Repository is a marker for an actual spring data repository. Since your CrudRepository extends Repository spring is trying to initialize a Spring managed repository named crudRepository for T (which essentially tranlates to Object). Since Object isn't managed by Hibernate it fails validation on startup and crashes.
#NoRepositoryBean will tell Spring to not generate a backing repository for a particular class that implements Repository.

InvalidDataAccessApiUsageException: Parameter value element did not match expected type

I'm trying to execute an IN query with by using Spring Data. My model looks like this:
#Entity
#Table(name = "customer", schema = "public", catalog = "postgres")
public class CustomerEntity {
private int id;
private String name;
private int balance;
private String bankId;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "balance")
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
#Basic
#Column(name = "bank_id")
public String getBankId() {
return bankId;
}
public void setBankId(String bankId) {
this.bankId = bankId;
}
And my repository interface looks like this:
#Repository
public interface TransactionsRepository extends JpaRepository<TransactionsEntity, Long> {
List<TransactionsEntity> findByCustomerIdIn(List<CustomerEntity> customerEntities);
}
The problem is that when I try to execute this code
List<TransactionsEntity> transactionsEntitiesList = transactionsRepository.findByCustomerIdIn(customerEntitiesList);
I get this exception:
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value element [org.example.domain.admin.CustomerEntity#6a1a2a4] did not match expected type [java.lang.String (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value element [org.example.domain.admin.CustomerEntity#6a1a2a4] did not match expected type [java.lang.String (n/a)]
Update: TransactionsEntity.class:
#Entity
#Table(name = "transactions", schema = "public", catalog = "postgres")
public class TransactionsEntity {
private String id;
private String amount;
private String customerId;
#Id
#Column(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Basic
#Column(name = "amount")
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
#Basic
#Column(name = "customer_id")
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TransactionsEntity that = (TransactionsEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (amount != null ? !amount.equals(that.amount) : that.amount != null) return false;
if (customerId != null ? !customerId.equals(that.customerId) : that.customerId != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (amount != null ? amount.hashCode() : 0);
result = 31 * result + (customerId != null ? customerId.hashCode() : 0);
return result;
}
}
As it says in the exception Spring expects a String because your customer_id in your TransactionEntity is a String, but you are inputting a CustomerEntity. Instead you should input a List<String> with the list of your customer ids.
Btw shouldn't your customer_id be an int assuming you set it to the id of your CustomerEntity?
Then you could do something like
List<Integer> customerIds = customerEntitiesList.stream().map(CustomerEntity::getId).collect(Collectors.toList());

Incorrect Hibernate HQL / DAO function / while coding Spring Security - Annotations

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.

Save entity only if exact entity doesn't exist

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.

How to make it in JPA Criteria?

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();

Categories