SQL Query with Entity Manager - java

I've been thinking about how to create a proper query for my purpose but I'm not sure how should I approach it. It's a Spring web app, the website is similar to Twitter.
What I'm trying is to get the messages from who the user that requested the function follows. Saying shortly, a Twitter timeline, there are the classes:
User class
//Imports
#Entity
#Table (name = "USUARIOS")
public class UsuarioVO implements Serializable {
//Not important class attributes and their getters/setters
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "USER_FOLLOW",
joinColumns = #JoinColumn(name = "FOLLOWED_ID"),
inverseJoinColumns = #JoinColumn(name = "FOLLOWER_ID"))
public Set<UsuarioVO> getFollowers() {
return followers;
}
public void setFollowers(Set<UsuarioVO> followers) {
this.followers = followers;
}
public void addFollower(UsuarioVO user) {
followers.add(user);
user.following.add(this);
}
#ManyToMany(mappedBy = "followers")
public Set<UsuarioVO> getFollowing() {
return following;
}
public void setFollowing(Set<UsuarioVO> following) {
this.following = following;
}
public void addFollowing(UsuarioVO user) {
user.addFollower(this);
}
}
Message class
#Entity
#Table(name = "MENSAJES")
public class MensajeVO implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2819136255644301650L;
private Long id;
private UsuarioVO sender;
private String body;
private Date fecha;
private HashtagVO hashtag;
public MensajeVO() {}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "ID_SENDER")
public UsuarioVO getSender() {
return sender;
}
public void setSender(UsuarioVO sender) {
this.sender = sender;
}
#Column(name = "BODY")
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "FECHA_ENVIO")
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_HASHTAG")
public HashtagVO getHashtag() {
return hashtag;
}
public void setHashtag(HashtagVO hashtag) {
this.hashtag = hashtag;
}
}
The first approach I thought was getting the Set of following from the user and query each one of them to retrieve the messages, but there is a problem with that, I want to order the query by date, with that approach it would only order by date the message of each user, like:
User1 messages ordered by Date
User2 messages ordered by Date
etc..
I was thinking about doing this with an Inner Join, but I'm not sure how should I build the query. An example of a working query:
public Set<MensajeVO> findByUser(Long userid) {
Query query = this.entityManager.createQuery(
"SELECT m FROM MensajeVO m WHERE m.sender.id = ?1 ORDER BY m.fecha DESC", MensajeVO.class);
query.setParameter(1, userid);
return new HashSet<MensajeVO>(query.getResultList());
}
Thanks in advance.
EDIT
In SQL this is the query
SELECT * FROM mensajes INNER JOIN user_follow ON mensajes.ID_SENDER = user_follow.FOLLOWED_ID WHERE user_follow.FOLLOWER_ID = ?
But I don't know how to get user_follow in Java, since is a ManyToMany field.

Figured it out, posting it in case it helps anyone:
Query query = this.entityManager.createQuery(
"SELECT m FROM MensajeVO m WHERE EXISTS(SELECT 1 FROM UsuarioVO u JOIN u.followers fr WHERE fr.id = ?1) OR m.sender.id = ?2 ORDER BY m.fecha DESC", MensajeVO.class);
query.setParameter(1, userid);
query.setParameter(2, userid);
Search for the messages sent by people followed by the user or messages sent by the user.

Related

Hibernate problems with join fetch "Cannot join to attribute of basic type"

I'm having problems with loading entities with a one-to-one relationship from a sqlite database.
When I use a plain CriteriaQuery to load them everything works fine. But I've read somwhere that for the performance it's better to join the two tables the data is coming from in the query so hibernate won't make 2 queries out of it.
I am getting a BasicPathUsageException: Cannot join to attribute of basic type when I am trying to create a Fetch thingy.
This is the method I use to create the query:
private List<Task> loadTasks() {
try {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Task> taskQuery = builder.createQuery(Task.class);
Root<Task> taskTable = taskQuery.from(Task.class);
Fetch<Task, TaskType> fetch = taskTable.fetch(TaskType_.ID, JoinType.LEFT); //<- exception is pointing here
taskQuery.where(builder.equal(taskTable.get(TaskType_.ID).get("status"), "RECEIVED"));
List<Task> loadedTasks= session.createQuery(taskQuery).getResultList();
session.getTransaction().commit();
return loadedTasks;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This is the TaskType class:
#Entity(name = "TaskType")
#Table(name = "task_types")
public class TaskType implements Serializable {
private final SimpleIntegerProperty id = new SimpleIntegerProperty();
private final SimpleStringProperty name = new SimpleStringProperty();
#Id
#Column(name = "task_type_id", unique = true)
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id.get();
}
public void setId(int id) {
this.id.set(id);
}
#Column(name = "task_type_name", unique = true)
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public SimpleIntegerProperty idProperty() {
return id;
}
public SimpleStringProperty nameProperty() {
return name;
}
And this is the Task class which contains a task type object:
#Entity(name = "Task")
#Table(name = "tasks")
public class Task implements Serializable {
private final SimpleIntegerProperty id = new SimpleIntegerProperty();
private final SimpleStringProperty name = new SimpleStringProperty();
private TaskType type;
#Id
#Column(name = "task_id", unique = true)
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id.get();
}
public void setId(int id) {
this.id.set(id);
}
#Column(name = "task_name", unique = true)
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "task_type_id")
public TaskType getType() {
return type;
}
public void setType(TaskType type) {
this.type = type;
}
public SimpleStringProperty nameProperty() {
return name;
}
public SimpleIntegerProperty idProperty() {
return id;
}
How is this fetch() supposed to be used or how can I get the code to load all tasks including their task types? Am I using some annotation wrong?
I tried to look the exception up but I could not find any solution or understand how to apply it to my situation.
Thanks for any help!
The fetch method, just like the join methods, only work on associations.
You use the following instead
taskTable.fetch(Task_.TYPE, JoinType.LEFT);
taskQuery.where(builder.equal(taskTable.get(Task_.TYPE).get("status"), "RECEIVED"));

ResultSet error executing #Query in JPA Reposity, using nativeQuery = true

I am working on a web application using:
Spring Boot
PostgreSQL
JPA and Hibernate.
I have a table called role and another page. Among them there is a many-to-many table with ID's. What I'm trying to get is the list of pages that correspond to a role, so I'm trying to retrieve the list of pages from the id of the role and executing a query to bring the list. The problem is that I have an error in the ResultSet because it tells me that it does not find a column with the name page_id.
Example:
I have executed the query separately and this brings me results correctly.
select p.url from role_page rp, page p where rp.role_id = 6 and rp.page_id = p.page_id;
Output:
Output of the query
Then I made a call to the function to get the list and check it to make sure I get results.
public void rolesAndPages(){
List<Page> pages = pageRepository.findPagePerRole(6);
for (Page page: pages
) {
System.out.println(page.getUrl());
}
}
And throws the error described above:
org.postgresql.util.PSQLException: The column name page_id was not found in this ResultSet.
My Repository:
#Repository("pageRepository")
public interface PageRepository extends JpaRepository<Page, Long> {
#Query(value = "select p.url from role_page rp, page p where rp.role_id = ?1 and rp.page_id = p.page_id", nativeQuery = true)
List<Page> findPagePerRole(Integer id);
}
Role.java
#Entity
#Table(name = "app_role")
public class Role {
#Id
#SequenceGenerator(name="pk_sequence",sequenceName="messagesounds_id_seq", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="pk_sequence")
#Column(name="role_id")
private int id;
#Column(name="authority")
#NotEmpty(message = "*Please provide a name")
private String authority;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "role_page", joinColumns = #JoinColumn(name = "role_id"), inverseJoinColumns = #JoinColumn(name = "page_id"))
private Set<Page> pages;
public void setPages(Set<Page> pages) {
this.pages = pages;
}
public Set<Page> getPages() {
return pages;
}
public Role() {}
public Role(String authority) {
this.authority = authority;
}
public Role(String authority, Set<Page> pages){
this.authority = authority;
this.pages = pages;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
Page.java
#Entity
#Table(name = "page")
public class Page {
#Id
#SequenceGenerator(name = "pk_sequence", sequenceName = "messagesounds_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_sequence")
#Column(name = "page_id")
private int id;
#Column(name = "name_page")
#NotEmpty(message = "*Please provide a name")
private String name;
#Column(name = "url")
#NotEmpty(message = "*Please provide an url")
private String url;
#Column(name = "description")
#NotEmpty(message = "*Please provide a description")
private String description;
#ManyToMany(mappedBy = "pages")
private Set<Role> roles;
public Page() {
}
public Page(String name_page) {
this.name = name_page;
}
public Page(String name_page, Set<Role> roles) {
this.name = name_page;
this.roles = roles;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
The error is quite explicite, you need to select page_id column to make it work, not only p.url.
Try this to retrieve every column of Page :
#Query(value = "select p.* from role_page rp, page p where rp.role_id = ?1 and rp.page_id = p.page_id", nativeQuery = true)
Or, this to retrieve every columns of tables Page and Role_Page :
#Query(value = "from role_page rp, page p where rp.role_id = ?1 and rp.page_id = p.page_id", nativeQuery = true)
The both queries should work.
Did you tried :
#Query(value = "select p.url from role_page rp, page p where rp.id = ?1 and rp.id = p.id")

Hibernate error: Illegal Attempt to deference collection

Hello I have a one to many relationship between a reservation and rooms and its unidirectional. A reservation might have one to several rooms. Now I'm trying to search if a room is available based on certain dates, and type of room(i.e a king or queen).
My solution:
Find Rooms that are not present in the reservation table based and also based on the date criteria.
Room model:
#Entity
#Table(name="room")
public class Room implements java.io.Serializable {
private static final long serialVersionUID = 10L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="roomId", nullable = false)
private long Id;
#Column(name="roomNumber", length = 4, nullable = false) //room number with max length of 4 digits
private String roomNumber;
#Column(name="type", nullable = false, length=10) //queen or king
private String roomType;
#Column(name="properties", nullable = false, length=15) //smoking or non-smoking
private String roomProperties;
#Column(name="price", columnDefinition = "DECIMAL(10,2)", nullable = false) //sets the precision of price to 2 decimal places
private double price;
public Room() {}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public long getId() {
return Id;
}
public void setId(long id) {
this.Id = id;
}
public String getRoomNumber() {
return roomNumber;
}
public void setRoomNumber(String roomNumber) {
this.roomNumber = roomNumber;
}
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public String getRoomProperties() {
return roomProperties;
}
public void setRoomProperties(String roomProperties) {
this.roomProperties = roomProperties;
}
}
Reservation Table:
#Entity
#Table(name="Reservation")
public class Reservation implements Serializable {
private static final Long serialVersionUID = 100L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="reservation_Id", nullable = false)
private long Id;
public long getId() {
return Id;
}
public void setId(long id) {
Id = id;
}
#Column(name="CheckInDate")
private Date checkInDate;
#Column(name="CheckOutDate")
private Date checkOutDate;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "guestId", nullable = false)
private Guest guest;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "ReservedRooms", joinColumns = {#JoinColumn(name="resId",
referencedColumnName = "reservation_Id")}, inverseJoinColumns = {#JoinColumn(name="roomId",
referencedColumnName = "roomId")})
private List<Room> roomList;
#Column(name="roomsWanted")
private int roomsWanted;
public int getRoomsWanted() {
return roomsWanted;
}
public void setRoomsWanted(int roomsWanted) {
this.roomsWanted = roomsWanted;
}
public Date getCheckInDate() {
return checkInDate;
}
public void setCheckInDate(Date checkInDate) {
this.checkInDate = checkInDate;
}
public Date getCheckOutDate() {
return checkOutDate;
}
public void setCheckOutDate(Date checkOutDate) {
this.checkOutDate = checkOutDate;
}
public Guest getGuest() {
return guest;
}
public void setGuest(Guest guest) {
this.guest = guest;
}
public List<Room> getRoomList() {
return roomList;
}
public void setRoomList(List<Room> roomList) {
this.roomList = roomList;
}
}
Now method to perform the search availability:
#Override
#Transactional
#SuppressWarnings("unchecked")
public boolean checkAvailability(SearchCriteria searchCriteria) {
String hql = "from Room as r where r.roomType = :roomType1 and r.roomProperties = :roomProperties1 " +
"and r.Id not in (Select res.roomList.Id from Reservation as res left outer join res.roomList " +
"where res.checkInDate <=:checkInDate1 and res.checkOutDate >= :checkOutDate1 " +
" and R.Id = res.roomList.Id) ";
Query query = getSession().createQuery(hql);
query.setParameter("roomType1", searchCriteria.getRoomType());
query.setParameter("roomProperties1", searchCriteria.getRoomProperties());
query.setParameter("checkInDate1", searchCriteria.getCheckInDate());
query.setParameter("checkOutDate1", searchCriteria.getCheckOutDate());
List<Room> roomList = query.list();
if(roomList.isEmpty()) {
return true;
}
return false;
}
But it complains and gives the error:
illegal attempt to dereference collection [reservatio1_.reservation_Id.roomList] with element property reference [Id]
Please what I'm doing wrong as I'm new to hibernate
When you join a collection, you have to name it. You can't use it directly (dereference).
in (Select ROOMS.Id from Reservation as res
left outer join res.roomList AS ROOMS
where res.checkInDate <=:checkInDate1 and res.checkOutDate >= :checkOutDate1
and R.Id = ROOMS.Id)

JsonMappingException with Arrays of object in spring-jpa

i get an error when i try to get an item from my dbms. following error
com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.pharmawizardcabinet.core.entity.cabinet.Cabinet.listaFarmaci, could not initialize proxy - no Session (through reference chain: com.pharmawizardcabinet.web.beans.ResponseCabinet["cabinet"]->com.pharmawizardcabinet.core.entity.cabinet.Cabinet["listaFarmaci"])
this is my conteiner
#Entity
#Table(name = "Cabinet")
public class Cabinet implements Serializable {
private static final long serialVersionUID = 7311927404447970875L;
#Id
#Column(name = "Id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "cabinet")
private List<Farmaco> listaFarmaci;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "user")
private User user;
#Column(name = "timestamp")
#Temporal(TemporalType.DATE)
private Date setLastModified;
public Cabinet() {
}
#PostPersist
#PostUpdate
private void setLastUpdate() {
this.setLastModified = new Date();
}
public List<Farmaco> getListaFarmaci() {
return listaFarmaci;
}
public void setListaFarmaci(List<Farmaco> listaFarmaci) {
this.listaFarmaci = listaFarmaci;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public Date getSetLastModified() {
return setLastModified;
}
public void setSetLastModified(Date setLastModified) {
this.setLastModified = setLastModified;
}
}
and this is the item
#Entity
#Table(name = "Farmaco")
public class Farmaco implements Serializable {
private static final long serialVersionUID = -152536676742398255L;
public Farmaco() {
// TODO Auto-generated constructor stub
}
#Column(name = "nome_farmaco")
private String nome;
#Column(name = "codice")
private String codice;
#Column(name = "azienda")
private String azienda;
#Id
#Column(name = "Id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
#Column(name = "scadenza")
#Temporal(TemporalType.DATE)
private Date scadenza;
#Enumerated(EnumType.STRING)
#Column(name = "posologia")
private Posologia posologia;
#Column(name = "quantita")
private Integer quantita;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "note")
private Note note;
#ManyToOne(cascade =CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "cabinet_id")
private Cabinet cabinet;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCodice() {
return codice;
}
public void setCodice(String codice) {
this.codice = codice;
}
public String getAzienda() {
return azienda;
}
public void setAzienda(String azienda) {
this.azienda = azienda;
}
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public Date getScadenza() {
return scadenza;
}
public void setScadenza(Date scadenza) {
this.scadenza = scadenza;
}
public Posologia getPosologia() {
return posologia;
}
public void setPosologia(Posologia posologia) {
this.posologia = posologia;
}
public Integer getQuantita() {
return quantita;
}
public void setQuantita(Integer quantita) {
this.quantita = quantita;
}
public Note getNote() {
return note;
}
public void setNote(Note note) {
this.note = note;
}
public Cabinet getCabinet() {
return cabinet;
}
public void setCabinet(Cabinet cabinet) {
this.cabinet = cabinet;
}
}
controller is this
#Component("managerCabinet")
public class ManagerCabinet {
private static Logger logger = Logger.getLogger(ManagerCabinet.class);
#PersistenceContext(name = "pwcabinet-jpa")
private EntityManager entityManager;
#Transactional
public Cabinet getCabinetByUser(User user) {
logger.debug("[getCabinetByUser] user: " + user.getId());
return _getCabinetByUser(user);
}
private Cabinet _getCabinetByUser(User user) {
logger.debug("[_getCabinetByUser] user: " + user.getId());
User find = entityManager.find(User.class, user.getId());
Query searchCabinetByUser = entityManager.createQuery("Select c from Cabinet c where c.user = :userId", Cabinet.class);
searchCabinetByUser.setParameter("userId", find);
Cabinet cabinetSearch = (Cabinet) searchCabinetByUser.getSingleResult();
cabinetSearch.setUser(find);
return cabinetSearch;
}
}
but i continue to get error.
if i use the annotation #JsonIgnore in this way
#JsonIgnore
public List<Farmaco> getListaFarmaci() {
return listaFarmaci;
}
they works, but i need this information in my result. how i solve it?
When your method private Cabinet _getCabinetByUser(User user) returns the Cabinet instance is then in the 'detached' state, viz. is no longer associated with a persistence context.
When an item is in a detached state non-eagerly fetched associations can longer be accessed.
As the default fetch for #OneToMany is Lazy then in your case
#OneToMany(cascade = CascadeType.ALL, mappedBy = "cabinet")
private List<Farmaco> listaFarmaci;
the field listaFarmaci can no longer be accessed once the loaded Cabinet is detached from the persistence context.
You have various means of dealing with this which would include:
Marking the field as being eagerly fetched (not good as will always be eagerly fetched regardless of whether required or not).
Forcing the persistence context to remain open until all processing is done typically referred to as the OpenSessionInView pattern (or anti-pattern) depending on your point of view: http://java.dzone.com/articles/open-session-view-design
Ensuring all data required for use case is initialized before detachment. There are various ways of achieving this:
Simply accessing the collection is some way e.g. by calling size() but this may not work with all JPA providers.
Specifying FETCH JOIN in your JPQL query which loads the Cabinet (although this has side effects). http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Join_Fetching

trying to run a named query

I’m doing the following:
#Entity
#SqlResultSetMapping(name="getxxxx",
entities=#EntityResult(xxxx.class,
fields = {
#FieldResult(name="x1", column = "x1"),
#FieldResult(name="x2", column = "x2")}))
#NamedNativeQuery(name=" getxxxx ",
query="select x1, x2 from yyyy",
resultSetMapping=" getxxxx ")
} )public class xxxx{
.
.
.
public xxxx() {
}
i get an error:
"Table "xxxx" cannot be resolved", the class xxxx is not a table mapped into my source,
I’m trying to query the DB and return the results into my class
is it possible?
In this situation the first thing I would try would be to remove the #Entity annotation. And then change either the class name or the native query name so that one of them is "xxxx" and one of them is "zzzz," so that I was sure I knew which thing the runtime was complaining about.
It sounds like xxxx should not be an entity bean, since JPA is not happy with returning results in non-entity beans. You must instead call createNativeQuery with just the SQL String. Then call query.getResultList() to fetch the result as a List(Object[]) and use this to fill your non entity result bean.
A few years back I wrote a blog post, that might help you perform advanced native queries with JPA.
Yes, this is possible, but a little tricky. Here's a complex example that should cover most of the bases. In this example:
You have an INVOICE object with a due date;
Each INVOICE has a many-to-one relationship with a COMPANY;
Each INVOICE also has a zero- or one-to-many relationship with a set of ITEMS
Here is the schema:
CREATE TABLE "public"."invoice" (
id SERIAL,
company_id int,
due_date date,
PRIMARY KEY(id)
);
CREATE TABLE "public"."item" (
id SERIAL,
invoice_id int,
description text,
PRIMARY KEY(id)
);
CREATE TABLE "public"."company" (
id SERIAL,
name text,
PRIMARY KEY(id)
);
The INVOICE object (incredibly convoluted example for the sake of completeness):
#Entity
#Table(name = "invoice")
#Loader(namedQuery = "loadInvoiceObject")
#NamedNativeQuery(name="loadInvoiceObject",
query="SELECT " +
"inv.id," +
"inv.due_date," +
"co.*," +
"it.*," +
"FROM invoice inv " +
"JOIN company co ON co.id = inv.company_id " +
"LEFT OUTER JOIN item it ON it.invoice_id = inv.id " +
"WHERE inv.id = :id",
resultSetMapping = "invoicemap")
#SqlResultSetMapping(name = "invoicemap",
entities = {
#EntityResult(entityClass = Invoice.class),
#EntityResult(entityClass = Company.class),
#EntityResult(entityClass = Item.class)
}
)
public class Invoice {
private Integer id;
private Date dueDate;
private Company company;
private List<Item> items = new ArrayList<Item>();
public Invoice() { /* no-args constructor */ }
#Id
#Column(name = "id", nullable = false)
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
#Column(name = "due_date")
#Temporal(TemporalType.DATE)
public Date getDueDate() { return dueDate; }
public void setDueDate(Date dueDate) { this.dueDate = dueDate; }
#ManyToOne(optional = false)
#JoinColumn(name = "company_id", nullable = false)
public Company getCompany() { return company; }
public void setCompany(Company company) { this.company = company; }
#OneToMany(mappedBy = "invoice")
public List<Item> getItems() { return items; }
public void setItems(List<Item> items) { this.items = items; }
}
The ITEM object:
#Entity
#Table(name = "item")
public class Item {
private Integer id;
private String description;
private Invoice invoice;
public Item() { /* no-args constructor */ }
#Id
#Column(name = "id", nullable = false)
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
#Column(name = "description")
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
#ManyToOne(optional = false)
#JoinColumn(name = "invoice_id", nullable = false)
public Invoice getInvoice() { return invoice; }
public void setInvoice(Invoice invoice) { this.invoice = invoice; }
}
The COMPANY object:
#Entity
#Table(name = "company")
public class Company {
private Integer id;
private String name;
private List<Invoice> invoices = new ArrayList<Invoice>();
public Company() { /* no-args constructor */ }
#Id
#Column(name = "id", nullable = false)
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
#Column(name = "name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
#OneToMany(mappedBy = "company")
public List<Invoice> getInvoices() { return invoices; }
public void setInvoices(List<Invoice> invoices) { this.invoices = invoices; }
}

Categories

Resources