How to retrieve multiple entries from table into one list? - java

thanks for helping ;)
I'm new to hibernate and wanna try it for my private project.
What i want to do is: I want to have a class like
public class Playlist {
private long id;
private String name;
private long owner_ID;
private ArrayList<String> urls;
}
Where the list should contain urls to some songs.
At the moment I have one entry in my db for each url. Is there a better way to do that?
And to my main question: How can I recieve/save the list?
I can get a "normal" table entry rn but I haven't worked with Hibernate and Lists/ArrayLists in combination jet.
Hope you can help me ;)
If additional information is required feel free to ask.

Since the urls is a basic value (String) you can use #ElementCollection.
#Entity
public class Playlist {
#Id
private Long id;
private String name;
private long owner_ID;
#ElementCollection
private List<String> urls;
}
This mapping links two tables:
playlist table which has id, name, owner_ID columns
playlist_urls table which has playlist_id and urls columns.
For more information take a look at here.

Related

How to do one to many relationships in JDBC?

I have class two classes
i want to perform one to many relationship
public class Teacher {
private int id;
private String name;
private List<Class> classes;
}
public class Class {
private int id;
private String className;
}
I need to retrieve data and print data from the database
Teacher Classes
Kumar A1,B3,B4
Deepa A1,A2,C1
Alex B2,D1,D2
I don't Know how to retrive one to many relationship data in JDBC
please suggest me what should i do?
I do know about 2 ways to do it with jdbc
You need to select all teachers first, then for each teacher select his classes.
select * from teacher
then map results to your teacher class then on java side make a for each loop and fetch class by teacher_id for each teacher
select * from class where teacher_id = :teacher_id
You can select all teachers and classes like that:
select * from teacher t
left join class c on c.teacher_id = t.teacher_id
but you will get duplicate data of teacher becouse in each row you will fetch data for teacher also and you will need to organize it on Java side.
So I've been working recently with Spring JDBC myself. This is something similar with what I've come up with by reading here and there. I really appreciate the simplicity of JDBC combined with the domain driven approach:
public class Teacher {
#Id private int id;
private String name;
#MappedCollection(idColumn = "teacher_id", keyColumn = "teacher_key")
private List<Class> classes;
//setters and getters
}
public class Class {
private int id;
private String className;
//setters and getters
}
Then you need to create the repository interface by extending CrudRepository from Spring JDBC, you don't need to create an extra repository to e.g. save Class data through Teacher :
interface TeacherRepository extends CrudRepository<Teacher, Integer> {}
The TeacherRepository will have the typical CRUD methods that allow you to read or write data from/to the database.
The sql code (this is postgres like, change to your specific dialect) would be something like this:
create table teachers(
id serial primary key,
name text
)
create table classes(
id serial primary key,
class_name text,
teacher_id int references teachers(id),
teacher_key int
)
Where the teacher_key column is used to return an ordered list of classes. If you don't care about the classes ordering you can just return a set instead of a list:
public class Teacher {
#Id private int id;
private String name;
#MappedCollection(idColumn = "teacher_id")
private Set<Class> classes;
//setters and getters
}
public class Class {
private int id;
private String className;
//setters and getters
}
the sql code:
create table teachers(
id serial primary key,
name text
)
create table classes(
id serial primary key,
class_name text,
teacher_id int references teachers(id)
)
Here are my sources:
https://www.youtube.com/watch?v=ccxBXDAPdmo
https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates
https://lumberjackdev.com/spring-data-jdbc
https://docs.spring.io/spring-data/jdbc/docs/current/reference/html/#jdbc.repositories

Hibernate many-to-many set primary/foreign keys in thrid table

I have 3 java classes, two entites and the third is relationship between them. I want to map them in hbm.xml, but I don't know how, I can't find any example on internet
public class Product {
private String _description;
private String _name;
private double _price;
private Long _productId;
private int _quantity;
public class Order {
private Long _orderId;
private List<OrderProduct> _productList;
private User _user;
public class OrderProduct {
private Order _order;
private Product _product;
How to map this in xml, to this thrid class "OrderProduct" stores only order and product as primary and foreign keys.
Thanks in advice
There is no need for OrderProduct entity. You can define the mapping in the hbm Itself. Please see the below link to understand how its done.
https://www.mkyong.com/hibernate/hibernate-many-to-many-relationship-example/

hibernet one to many on web

I am completely new in Hibernate ORM world, recently reading mapping specially one-to-many relation. But i am facing some problem to understand.
I am using this link to understand hibernate relation.
https://dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-one-to-many-using-annotations-1.html
please have a look the code.
public class Student {
private long studentId;
private String studentName;
private Set<Phone> studentPhoneNumbers
//setter getter
}
public class Phone {
private long phoneId;
private String phoneType;
private String phoneNumber;
//setter getter
}
i understand it.
confusion is here.
Set<Phone> phoneNumbers = new HashSet<Phone>();
phoneNumbers.add(new Phone("house","32354353"));
phoneNumbers.add(new Phone("mobile","9889343423"));
Student student = new Student("Eswar", phoneNumbers);
session.save(student);
Does this only one code session.save(student), store value in both table ? if no then why we didn't write code to save phoneNumbers like session.save(phoneNumbers).
Once this above code is executed then the value will be stored in both table or object(STUDENT and PHONE) right ?. I think each time we execute this code, this code insert value in both table. i don't like it. i want value should be store on only second table(PHONE).
So how will i store value in only PHONE object ?
or how will we implement this relation where user will select STUDENT through combobox and fill value in PHONE object through simple textboxes. then finally save it.like product/category.
3.please help or suggest some good tutorial where hibernate is implemented (specially one-to-many and many to many relation) in web application. i have seen many tutorial but all these are implemented through main method.
sorry for the poor English
thanks.
Yes it should save both student and phone number in their own table. If you annotate the right way. Student should be something like this:
#Entity
#Table(name = "student")
public class Student {
#id
#GeneratedValue
private long studentId;
#column(name = "studentName")
private String studentName;
#OneToMany
private Set<Phone> studentPhoneNumbers
//setter getter
}
public class Phone {
private long phoneId;
private String phoneType;
private String phoneNumber;
//setter getter
}
Then there is also some configuration to do. I'd advice you to read this tutorial: https://www.tutorialspoint.com/hibernate/index.htm
In the case of your code it doesn't much. But if you configure hibernate the right way you can decide in which table/column a value should be saved
Hibernate tutorial - Tutorials point

Show values of a list?

I have two beans with List and #ManyToMany annotation. Now I created a JasperReports's report and I want to show values of lists.
I created the Field at report, after I added a Component List in my Detail Band and when I try display the report doesn't work.
Here how I am trying
#Entity
public class Conta
#Id #GeneratedValue
private Long id;
#ManyToMany
private List<PlanoDeConta> plano;
#Entity
public class PlanoDeConta{
#Id #GeneratedValue
private Long id;
#NotNull #Column(unique=true)
private String planoConta;
#ManyToMany(mappedBy="plano");
private List<Conta> conta;
}
At JasperReports's report I'm trying show values Field type List, for example: plano.PlanoConta but not works. I'm tried show values on Component List also.
I want show planoConta value.
How to I can do this ?
What I did in that situation was make a subreport and then put it in a group band, then in the properties of the subreport, one perhaps should make the
connection type = datasource by expression.
Then make
the datasource expression = new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{plano}).
Then in my subreport i would have the fields: Id, planaConta, etc.
If you have any questions, just ask.

How to save a mapping of similar data in DB using JPA

I don't know how to design this rdbms problem:
Let's say, I have a customer, who is making a purchase. By making the purchase he leaves his data. I have a second dataset with real customer data. After collecting the data, I want to find a mapping of the collected customer data to the real customers by an algorithm.
It's still unclear how to save this mapping/these links created by the algorithm.
Proposal:
#Entity
public class Purchase{
#OneToOne
private Customerdata customerData;
}
#Entity
public class CustomerData{
private String firstName;
private String Lastname;
private String city;
}
#Entity
public class RealCustomer{
#OneToMany(cascade=CascadeType.ALL, mappedBy ="RealCustomer")
private List<CustomerData> customerData = new ArrayList<CustomerData>();
private String firstName;
private String Lastname;
private String city;
}
Now I can save my assumed mapping from RealCustomer data to customer data in the customerData list.
I guess that's not the best idea?
Hoping for nice suggestions from you. Can I take advantage of the similarity of real customer data and obtainer customer data.
Please note that I want to keep inconsistent data e.g. even if city is similar ('Washington D.C.' and 'Washington'. I don't want to lose this information that I can run the matching algorithm later again.
Note: I'm okay, if you provide me the rough idea. Java/JPA-Code not necessary.
Thank you very much in advance!
You can do something like below
#Entity
public class Purchase{
#OneToOne
private Customer customer;
}
#Entity
public class Customer{
private String firstName;
private String Lastname;
private String city;
//Below association will only come in picture if customer has real customer data available when you are collecting the data this way you can clearly identify and separate collected vs real customers
#OneToOne
Customer realCustomer;
}

Categories

Resources