Spring mvc with hibernate #OneToMany relationship mapping - spring

enter image description hereI have two table one is Credit and second is Debit. I want #OneToMany relationship. in credit table only single row of data and In debit table multiple row of data
Credit table:
cid
openingBalance
date
debittotal
drawertotal
debittotalplusdrawertotal
todaybusiness
all row of only single row data
Debit table:
did
amounnt
description
amount and description multiple data add
I am using Spring mvc with hibernate project structure is just like below
controller
entity
dao
daoImpl
service
serviceImpl
How to create enitiy with #OneToMany Relationship and when I save that data then all data will save at time into two table

You need Cascade persist for this.
#OneToMany(mappedBy="credit", cascade=CascadeType.PERSIST)
List<Debit> debits;
and then in your dao:
Credit credit = new Credit(......);
credit.setDebits(/*the list of debits*/)
entityManager.persist(credit);
or if you're using springdata jpa :
repository.save(credit);

Related

Entity Graph for nested associations of tables in Spring JPA

There are 3 tables in my db:
SalesOrderMaster
SalesOrderDetail
CustomerMaster
I have repository class SalesOrderDetailRespository.java which has this method findAll()
#EntityGraph(attributePaths = {"SalesOrderMaster"}, type = EntityGraph.EntityGraphType.FETCH)
List<SalesOrderInfo> findAll(#Nullable Specification<SalesOrderInfo> spec);
This is till now fetching the SalesOrderMaster record and associated SalesOrderDetails records. Now my requirement is in SalesOrderInfo class , I have added a new property for showing the Customer Information like Name , country which are there in CustomerMaster table.
The customerMaster table is related to SalesOrderMaster by customerId column. How do I add CustomerMaster table in the existing EntityGraph so that I can get this info?

Spring Data JDBC save to two tables

How to save an entity to two tables at the same time using Spring Data JDBC?
class MyEntity {
/* to be saved in table #1 */
int ID; /* auto-generated in table #1 */
String name;
/* to be saved in table #2 */
int titleID; /* auto-generated in table #2 */
String title;
}
I am new to Spring. It took me two days to find out how to do INNER JOIN query using Spring Data JDBC.
There is no special support in Spring Data JDBC for this.
You can do one of the following:
create an updatable view on the two tables, that joins the two tables and map your entity to that view. In order to be able to update both tables you might have to add triggers to the view, depending on the capabilities of your database.
You might split the entity into two with a 1:1 relationship with each being persisted in one table.

Delete Values from Join Table spring boot

I have two tables students and subjects. A student can have more than one subject and vice versa. I have two model classes and vave joined using Many to Many relationship in spring boot and JPA.My problem is how I can delete values from my join table. But I can't figure out how I can do delete from join table. For Student and Subject Model I delete comfortably using deleteById() function.This is my code:
#ManyToMany
#JoinTable(
name = "student_subject",
joinColumns = #JoinColumn(name = "student_id"),
inverseJoinColumns = #JoinColumn(name = "subject_id"))
private Set<SubjectModel> subjects;
//and my repository Class
#Repository
public interface SubjectDao extends JpaRepository<SubjectModel, Integer> {}
You have to delete the corresponding objects form both sides of the link, and then save them.
myStudent.getSubjects().remove(mySubject);
mySubject.getStudents().remove(myStudent);
SubjectDao subjectDao = new SubjectDao();
subjectDao.save(mySubject);
Here another examle: Hibernate: delete many-to-many association
You have two table Student and Subject.
And I suppose you want is delete one of the subject from a student.
For that you should let jpa delete the row from subject and student-subject association table. And dont need to user SubjectRepository.
Take a look.
Student firstStudent=studentRepository.findById(1);
Set<SubjectModel> subs=firstStudent.getSubject();
subs.clear();
firstStudent.setSubject(subs);
studentRepository.save(firstStudent); // this method will delete the row from assiciation table as well as the subject table.

How to connect three tables using only one entity/class in Spring & Hibernate

I have only one entity which is School - a class (example). I have 7 fields in there and those fields are from 3 different tables. The first table for example is called Classroom, second is the Teachers, third is Subject. The teachers and subject table are connected by a pk: subject_id while the classroom table and teachers table are connected by classroom_id.
I tried secondary tables but it looks like it's not correct. How to connect those tables inside a single entity and write a query in the DAO IMPLementation
You should use Entity per Table.
If you need to select into non database related Model class, you can be done easily with spring-data-jpa.
After create the Model class (like School) just use the following sample to query:
class ProgrammerNameAndCity{
fields...
allArgConstructor...
}
public interface ProgrammerRepository extends JpaRepository<Programmer,Long> {
#Query(" select new com.zlrx.database.pojo.ProgrammerNameAndCity(p.name,p.address.city) " +
"from Programmer p where p.idNumber=?1")
ProgrammerNameAndCity findNameAndCityByIdNumber(String idNumber);
}
In this example the programmer has an address field (OneToOne), but you can create any kind of query, the important thing here is the constructor call of the model.
If you want to use plain sql or impl class instead of interface to query, you can use Spring's RowMapper too.
class ProgrammerNameAndCity{
fields...
allArgConstructor...
}
public interface ProgrammerRepository extends JpaRepository<Programmer,Long> {
#Query(" select new com.zlrx.database.pojo.ProgrammerNameAndCity(p.name,p.address.city) "
+ "from Programmer p where p.idNumber=?1")
ProgrammerNameAndCity findNameAndCityByIdNumber(String idNumber);
}

Spring Rest Error: Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING

I am using rest services with spring data . when i get data from single table its return proper result in json format . but when i use many to many association between entities using hibernate i am getting an un acceptable result with following error in chrome's console .
Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
My result looks like there just one row repeating itself , and its a particularly that field which is being used in new generated table by association.
[{"id":7,"name":"Milk pack","description":"haleeb","imageUrl":"milk.jpg","price":350.00,"category":null,"orderDetail":[]},{"id":8,"name":"oil","description":"olive oil ","imageUrl":"/resources/uploads/olive.png","price":670.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design ","imageUrl":"/static/uploads","price":34569.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design ","imageUrl":"/static/uploads","price":34569.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design ","imageUrl":"/static/uploads","price":34569.00,"category":null,"orderDetail":[{"id":263,"productlist":[{"id":10,"name":"Mobile","description":"awesome design, slim design
.
.
.and so on
My entities are following
Product table
#ManyToMany(mappedBy = "productlist")
private List<OrderDetail> orderDetail =new ArrayList<OrderDetail>();
OrderDetail table
#ManyToMany
#JoinTable(
name="order_detail_productlist",
joinColumns=#JoinColumn(name="order_detail_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="productlist_id", referencedColumnName="id"))
private Set<Product> productlist = new HashSet<Product>();
I am using spring data jpa repository to get them
List<Product> findAll();
Note: which products those are not ordered yet that are working properly
You need the all log for the information, it maybe cause by loop when with jackson. So you need add #JsonIgnoreProperties.Please see http://stackoverflow.com/questions/3325387
My Problem is solved by using jackson 2.0 documentation
by Adding following annotation or OrderDetail table
#JsonBackReference
it breaks loop and show result properly

Resources