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/
Related
Consider a class Car
#Entity
class Car{
#Id
private UUID id; // primary key- this is the only thing that can't change.
private String name;
private String brand;
private string model;
#Data
public static class Key{
private String brand;
private String model;
}
}
There is a List.of(new Key("brand1","model1"), new Key("brand2","model2")).
How is it possible to find all those given cars by those keys?
Is it doable with only JPA methods? Do I need to write native query? Can I modify something (besides primary key) in order to do it correctly?
I went to the direction of #EmbeddedId and then use the JPA method findAllById(Collection ..) which would be the naïve solution, but it's impossible since it must be the primary key in order to work.
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
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.
I have three classes corresponding to three tables in mysql database. My classes are as follows.
#Entity
#Table(name="location")
public class Location {
private Integer locationId;
private Integer hospitalId;
private Integer regionId;
private String locationCode;
private String locationName;
private String locationType;
#Entity
#Table(name="hospital_region")
public class HospitalRegion {
private Integer regionId;
private Integer hospitalId;
private String regionCode;
private String regionName;
public enum Status{Active,Inactive}
private Status status;
#Entity
#JsonAutoDetect
#Table(name="hospital_information")
public class HospitalInformation{
private Integer hospitalId;
private String shortName;
private String name;
private Integer packageId;
private Date implementationDate;
private Date validFrom;
private Date validUpTo;
private Date lastUpload;
public enum SubscriptionType{Free,Complimentary,Paid}
private Integer totalUsers;
I am making a Web Services for a Hospital Application where one region could have multiple locations(one-to-many) and one hospital could be in multiple regions(one-to-many).
So what I want to do is make a web service that would insert the data into location table.The ideal workflow should be that I shall pass every field in Location class as a json object to insert a record into the Location table.
My Business Logic should first check for my regionId and hospitalId value passed in the json object . If the hospitalId which is passed corresponds to the value of regionId in region table, if both correspond, only then data should be saved.
So I need help about how to implement it as a Business Logic.Thanks in advance
You miss the JPA relationships concept.
Your attributes are not annotated in the 3 classes.
You need to read about:
#ManyToOne Relation
#OneToMany Relation
#OneToOne Relation
#ManyToMany Relation
See more:
JPA Foreign Key Annotation
JPA Relationships 1
JPA Relationships 2
Here's the thing :-)
We have two classes, Appointment and Hairdresser, both having the same, one ancestor (a static final Key: topParent) representing the HairSalon Key. The Appointment contains the Hairdresser like this:
#Parent
public Key parent;
public Key hairdresserKey;`
but when we try to filter out the appointment, it doesn't come up with a result. The parent in the hairdresserKey == null, that might be a clue, but we're kind of stuck now.
So can someone please tell us what's wrong with this query?
Thanks a lot!
appointment.hairdresserKey = new Key<Hairdresser>(topParent, Hairdresser.class, appointment.hairdresser.id);
appointment.parent = topParent;
Key<Hairdresser> queryKey = new Key<Hairdresser>(topParent, Hairdresser.class, appointment.hairdresser.id);
Objectify ofyTransaction = ObjectifyService.beginTransaction();
try {
List<Key<Appointment>> previousTimeSlotOneHour = ofyTransaction.query(Appointment.class)
.ancestor(topParent)
.filter("hairdresserKey", appointment.hairdresserKey)
.filter("timeSlot", appointment.timeSlot.getPreviousTimeSlot())
.filter("LENGTH", 1.0d).listKeys();
To clearify some more, this is how Appointment set up:
#Unindexed
public class Appointment implements Serializable {
#Id
public Long id;
#Indexed
public TimeSlot timeSlot;
#Transient
public WorkDay workDay;
#Transient
public Customer customer;
public Key customerKey;
public int END_TIME_HOUR;
public int END_TIME_MINUTES;
#Indexed
public TREATMENT treatment = TREATMENT.TREATMENT_CUT;
public int revisionNumber = -1;
/* QUERY Fields */
#Indexed
private String stringDate;
private double LENGTH;
#Parent
public Key parent;
private Date date;
#Transient
public Hairdresser hairdresser;
public Key hairdresserKey;
Found this:
This is almost certainly an indexing issue. In order for that query to work, you must define two indexes:
A single-property index on referenceKeyToC
A multi-property index on {ancestor, referenceKeyToC}
In Objectify 3.x, properties have single-property indexes by default, but if you have added #Unindexed to the class B then you need to put #Indexed on referenceKeyToC.
The multi-property index is defined in datastore-indexes.xml. If you run this query in dev mode, the environment should provide you with the snippet of xml needed.
That did the trick! Thanks for pointing in the right direction!