I'm using a JPARepository called PublicationRepository and want to find all Publications from a certain Person. This Classes are connected over the Class Author.
Person Class:
#Entity
public class Person {
#Id
private String email;
private String telefon;
private String password;
#OneToMany(mappedBy = "person")
Set<Author> Author;
}
Author Class:
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Author {
#Id
private int id;
#ManyToOne
#JoinColumn(name="Person_ID")
Person person;
#ManyToOne
#JoinColumn(name="Publication_ID")
Publication publication;
private String Date;
private String Writerstatus;
}
Publication Class
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Data
public class Publication {
#Id
private int id;
private String publicationname;
#OneToMany(mappedBy = "publication")
Set<Author> author;
}
And the PublicationRepository
public interface ProjektRepository extends JpaRepository<Projekt,Integer> {
}
public interface PublicationRepository extends JpaRepository<Publication,Integer> {
#Query(value = "SELECT pub.* FROM author as auth INNER JOIN publications as pub ON auth.publication_id = pub.id WHERE auth.person_id = ?1", native = true)
List<Publication> findAllPublicationsOfThisPerson(int personId);
}
Try this.
I would also recommend to annotate the entities with their table names:
#Table(name = "publication")
You use a manually build table for a Many-to-Many relationship Author
You could also delegate that to Spring Data Jpa by using #ManyToMany Annotation.
A good tutorial:
https://attacomsian.com/blog/spring-data-jpa-many-to-many-mapping
I am trying to set up a very simple database with two tables in Java and connect them using a specific connection table.
1st table Student consists of id, first_name and last_name.
2nd table Course consists of id and name.
The connection table called Enrollment should have course_id and student_id that originate from 1st and 2nd tables.
My problem is I don't know how to map the IDs when extending Spring Data JPA's AbstractPersistable, which has an auto-increment primary key field in it.
My code:
Student:
// Package
// Imports
#Entity
#Data #NoArgsConstructor #AllArgsConstructor
public class Student extends AbstractPersistable<Long> {
private String first_name;
private String last_name;
}
Course:
// Package
// Imports
#Entity
#Data #NoArgsConstructor #AllArgsConstructor
public class Course extends AbstractPersistable<Long> {
private String name;
}
I have tried different usages of #ManyToMany annotation but since the primary key ID is handled by AbstractPersistable, I have failed to map the 'invisible' IDs for the connection table.
I also know that the connection table and its columns can be named with #Column, #JoinColumn and #JoinTable. I haven't gotten that far yet.
Hi i would try something like this ...
#Entity
#Data #NoArgsConstructor #AllArgsConstructor
public class Student extends AbstractPersistable<Long> {
private String first_name;
private String last_name;
#ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "enrollment",
joinColumns = #JoinColumn(name = "student_id"),
inverseJoinColumns = #JoinColumn(name = "course_id")
)
private List<Course> courses;
}
#Entity
#Data #NoArgsConstructor #AllArgsConstructor
public class Course extends AbstractPersistable<Long> {
private String name;
#ManyToMany(mappedBy = "courses")
private List<Student> students;
}
In my code i have a oneToMany relation between customer class and item class. This means that, a customer may have one or many items.
Here is the customer code:
#Entity
#Data
public class customer {
#Id
#GeneratedValue
int id;
String name;
String lastname;
#Embedded
Address address;
#OneToMany
#Column(name="ITEM_ID")
List<item> item;
}
and it's the item class:
#Entity
#Data
public class item {
#Id
#GeneratedValue
int id;
String name;
String Serialnumber;
int price;
#ManyToOne
customer customer;
}
Then i have made some tests to try my queries in the models.
insert into item(id,name,Serialnumber,price) values(1,'bike','123',200);
insert into item(id,name,Serialnumber,price) values(2,'car','123',200);
insert into customer(id,name,lastname,Country,City,Street,No,item_id)
values(1,'Salman','Lashkarara','Iran','Tehran','Shariati','12',1);
insert into customer(id,name,lastname,Country,City,Street,No,item_id)
values(2,'Saba','Lashkarara','Iran','Tehran','Shariati','12',2);
insert into customer(id,name,lastname,Country,City,Street,No,item_id)
values(3,'Saba','Lashkarara','Iran','Tehran','Shariati','12',1);
But when i run my code, i face with the following error:
Column "ITEM_ID" not found; SQL statement:
insert into customer(id,name,lastname,Country,City,Street,No,item_id) values(1,'Salman','Lashkarara','Iran','Tehran','Shariati','12',1)
Please pay especial attention, that it is a java mvc-spring application and i create my models using the code, so there is no database to check the field item_id.
As you can see i have already added the #Column(name="ITEM_ID") to define the column.
You have to use #JoinColumn for association columns:
#OneToMany
#JoinColumn(name="ITEM_ID")
List<item> item;
some other options
#OneToMany(cascade=CascadeType.All, fetch=FetchType.EAGER)
#JoinColumn(name="ITEM_ID")
List<item> item;
in Item class
#ManyToOne(mappedBy="item")
customer customer;
you could do this i also have user class and bcr class, one user have many bcr so below code will help you
bcr.java
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_who_enter_demand", nullable = false)
public User getUserByUserWhoEnterDemand() {
return this.userByUserWhoEnterDemand;
}
public void setUserByUserWhoEnterDemand(User userByUserWhoEnterDemand) {
this.userByUserWhoEnterDemand = userByUserWhoEnterDemand;
}
user.java
#OneToMany(fetch = FetchType.LAZY, mappedBy = "userByUserWhoEnterDemand")
public Set<BudgetControlRegister> getBudgetControlRegistersForUserWhoEnterDemand() {
return this.budgetControlRegistersForUserWhoEnterDemand;
}
public void setBudgetControlRegistersForUserWhoEnterDemand(Set<BudgetControlRegister> budgetControlRegistersForUserWhoEnterDemand) {
this.budgetControlRegistersForUserWhoEnterDemand = budgetControlRegistersForUserWhoEnterDemand;
}
You can't map a table column without table:
#Entity
#Table(name = "ITEM_TABLE")
public class item {
...
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "CUSTOMER_ID_ITEM_TABLE")
private customer customer;
...
}
#Entity
#Table(name = "CUSTOMER_TABLE")
public class customer {
...
#OneToMany
#Column(name="ITEM_ID")
List<item> item;
}
I have two classes Student and Address.
Student{
stuid,
stuName,
}
Address{
street,
city,
stuid;//foriegn key Ref with Studnet
}
Can any one help me to map these two classes using hibernate??
You should learn what is OneToOne mapping in hibernate firstly.
Secondly if I would want to design then I would have address_id as foreign key in Student table and not student id.
//Table name will be taken as Student as you are not specifying it using #Table annotation
Student class
#Entity
public class Student{
#Id
#Column("stuid")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column("stuName")
private String name;
//setters and getters
}
Address class
#Entity
public class Address{
#Id
#Column("add_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column("street")
private String street;
#Column("city")
private String city;
#OneToOne(cascade={CascadeType.SAVE,CascadeType.MERGE})
#JoinColumn(name="stuid")
private Student student
//setters and getters
}
Suppose if a Student can have multiple Address entities then you need to have one-to-many relationship between Student and Address classes. A student should know what addresses they belong to and also as you need to save the student id in address table then the relationship becomes bi-directional.
The entities looks like this:
Student.java
#Entity
#Table(name = "student_tbl") // Optional, By default table name is student, if you want to give different name then use this line.
public class Student1 {
#Id
#GeneratedValue
private int stuid;
private String stuName;
#OneToMany(mappedBy = "student")
private List<Address> address = new ArrayList<Address>();
// Setters & Getters
}
Address.java
#Entity
#Table(name = "address_tbl")
public class Address {
#Id
#GeneratedValue
private int addressId;
private String street;
private String city;
#ManyToOne
#JoinColumn(name="stuid")
private Student1 student;
// Setters & Getters
}
I have 3 tables, each mapped to an entity. The entities are something like this:
#Entity
#Table(name = "person")
public class Person implements Serializable {
private int id;
//other fields
}
#Entity
#Table(name = "phone")
public class Phone implements Serializable {
private int id;
private Long price;
#ManyToOne
#JoinColumn(name = "personId")
private Person person;
#ManyToOne
#JoinColumn(name = "manufacturerId")
private Manufacturer manufacturer;
//other fields
}
#Entity
#Table(name = "manufacturer")
public class Manufacturer implements Serializable {
private int id;
private String name;
//other fields
}
What I want to do is to create a method that will return a list of Persons that have phones from a specified manufacturer with the price in a specified range.
EDIT: My dao class implements EntityJpaDao . I would need a solution that would work with this implementation.
Following query will return the Samsung mobile users with phone price range.
Criteria criteria = session.createCriteria(Phone.class, "phone");
criteria.createAlias("phone.person", "person")
criteria.add(Restrictions.between("phone.price", minPrice, maxPrice));
criteria.createAlias("phone.manufacturer","manufacturer");
criteria.add(Restrictions.eq("manufacturer.name", Samsung));
criteria.setProjection(Projections.property("person"));
List<Person> persons = criteria.list();