JPA hibernate ManyToOne relationship - java

I have 2 entities User and Venue. One user can have multiple venues. The table looks like this:
user_id is the foreign key in the Venue table.
I am trying to create a query for retrieving all Venues by user_id. This is what I have:
#Override
public List<Venue> findVenueByOwnerId(Long userId) {
return em.createQuery("select v from Venue v where v.user.id = :ownerId", Venue.class)
.setParameter("ownerId", userId)
.getResultList();
}
What am I doing wrong?
EDIT:
These are my mappings:
For User class:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false, nullable = false)
private Long id;
private String email;
private String username;
private String password;
private String firstName;
private String lastName;
#OneToMany
#JoinColumn(name = "user_id")
private List<Venue> venues;
For Venue class:
#Entity
public class Venue {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false, nullable = false)
private Long id;
private String name;
private String location;
private int capacity;
#ManyToOne
#Column(name = "user_id", updatable = false, nullable = false)
private User user;
And if I am trying to add getters and setters for the User in the Venue class, it throws me this error:
Caused by: org.hibernate.MappingException: Could not determine type for: razvan.sem3.project.model.User, at table: Venue, for columns: [org.hibernate.mapping.Column(user)]

Related

JPA entity with join column but not persisted

I have to entities
#Table(name = "BD_PERSON")
public class DBPerson {
#Id
#Column(name = "persion_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "car_id")
private Long car_id;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "car_id", referencedColumnName = "car_id", insertable = false, updatable = false)
private DBCar car;
#Column(name = "label")
private String label;
and
#Table(name = "BD_CAR")
public class DBCar {
#Id
#Column(name = "car_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "car_number")
private Integer carNumber;
#Column(name = "description")
private String description;
I want to be able to get the Person with the car entity but this should not persist to the database when updating.
But i should be able to update the car_id by itself as it relates the the id in the car table.
but when i try to test this by setting only the car_id i receive an Referential integrity constraint violation.
Because the car_id (FK)references the car_id (PK)
Is there any better way to accomplish what im trying to do?
The database already exists and is configured like this where the car_id is not an actual foreign key

How to get single column value using hibernate projection

I have a model class like below:
#Entity
#Table(name = "User")
public class UserModel implements Serializable{
private static final long serialVersionUID = 204096185700135310L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id", unique = true, nullable = false)
private Integer userId;
#Column(name = "user_login_name")
private String userLoginName;
#Column(name = "user_email_id")
private String userEmailId;
#Column(name = "user_password")
private String userPassword;
}
and I am writting a criteria with projection to get the userLoginName based on userId, like SELECT user_login_name from USER where user_id=1 :
public UserModel getUserByUserName(Integer userId) {
return (UserModel) HibernateService.getSession(sessionFactory)
.createCriteria(UserModel.class)
.setProjection(Projections.projectionList()
.add(Projections.property("userLoginName"), "userLoginName"))
.add(Restrictions.eq(AppConstant.USER_Id, userId))
.uniqueResult();
}
But it's throwing java.lang.String cannot be cast to com.app.aus.model.UserModel excetion. can someone help me here

Create relation between tables in JPA

I have main table merchants and second table terminals:
Merchant table:
#Entity
#Table
public class Merchants {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", updatable = false, nullable = false)
private int id;
#Column
private String name;
#Column
private String login;
}
Terminal table:
#Entity
#Table
public class Terminals {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", updatable = false, nullable = false)
private int id;
#Column
private int merchant_id;
#Column
private String mode;
}
I want to set merchant_id into table Terminals. I suppose that many to many will be proper relation. How I can create it?
If you have a Join Table:
On Merchants class:
#ManyToMany
#JoinTable(name="MER_TER", joinColumns=#JoinColumn(name="MERCH_ID", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="TERM_ID", referencedColumnName="id"))
private List<Terminals> terminalsList;
On Terminals class:
#ManyToMany(mappedBy="terminalsList")
private List<Merchants> merchantsList;
Page of reference: link
If you don't have a Join Table, try to look here: https://stackoverflow.com/a/25018992

SELECT * FROM with JPA for many-to-many relationship

I want to do a query(SELECT) with inner join using JPQL.
I'm using hibernate ddl auto to create tables from the entities.
I have 2 entities, they're relacionated among them by many-to-many relationship(One studio can be managed by many managers(user) and one manager(user) can manage many studios).
As you know, for many-to-many relationship, we use an intermediate table to do a "SELECT" with native SQL, but i'm using JPA and JPQL as query lenguage, so my question is: How to do JOIN SELECT between 2 tables relacionated among them by many-to-many relationship?
The entities below are my entities:
Entity 1(Studio):
#Entity
#Table(name = "studio")
public class Studio implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "studio_name", nullable = false)
private String studioName;
/**
* Indicates if the studio is active or inactive in the data base.
*/
#Column(name = "active")
private Boolean active;
/**
* The studio owner is the main manager for a studio.
*/
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "studio_owner", referencedColumnName = "id", nullable = false)
private User studioOwner;
/**
* Represents all the possible managers for this studio.
*/
#ManyToMany(fetch = FetchType.LAZY)
private List<User> studioManagers;
//--Getters and setter below
}
Entity 2(User):
#Entity
#Table(name = "userr")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "user_name", nullable = false, unique = true)
private String userName;
#Column(name = "email", nullable = false, unique = true)
private String email;
#Column(name = "password", length = 60)
private String password;
#Column(name = "name")
private String name;
#Column(name = "last_name")
private String lastName;
#Column(name = "user_state", nullable = false)
#Enumerated(EnumType.STRING)
private UserState userState;
/**
* The roles for this user.
*/
#ManyToMany(fetch = FetchType.EAGER)
private List<Role> roles;
public User() {
}
//--Getters and setter below
}
I'm sorry by me English, Im Spanish speaker.
In StudioRepository.java just write one method
List<Studio> findById(Integer id);
this will fetch studio with all the users associated with this studio.
eg:
Studio{
"id": 1,
"studioName": "some",
"studioOwner": [
{
.....
....
},
{
....
}
]
}

Hibernate one-to-one, No row with the given identifier exists exception

I need a link between two entities, so I use a one-to-one
#Entity
#Table(name = "T_USER")
public class User implements Serializable {
#Id
#Column(name = "user_id")
private int userId;
#Column(name = "login")
private String login;
#OneToOne(optional = true)
#JoinColumn(name="login", referencedColumnName="person_id", nullable = true, insertable = false, updatable = false)
private Person person;
}
#Entity
#Table(name = "T_PERSON")
public class Person implements Serializable {
#Id
#Column(name = "person_id")
private String personId;
#Column(name = "pin")
private String pin;
}
If there is no item for a particulary PERSON in table T_USER, user.getPerson throw a exception:
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [packagename.com.entity.Person#scabriou]
But If I have reference between the 2 tables in the db, the getter works!
I can't say if this the best solution but you could use the #NotFound annotation. E.g.
#NotFound(action = NotFoundAction.IGNORE)
private Person person;
I believe person will remain null and the exception will not be thrown.

Categories

Resources