Best way to run a M:N query in hibernate? - java

Trying to figure out how to use hibernate to call to get a list of the movies for a given genre?!
I tried getting a given genre then using the method from GenreDTO to get the set of movies.
Query hqlQuery = session.createQuery("FROM GenreDTO WHERE genre like :genre");
GenreDTO g = hqlQuery.setParameter("title","%" + term + "%").uniqueResult();
return g.getMovies();
Is there a better way?
CREATE TABLE Movie (
id INTEGER PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
title VARCHAR(255),
poster VARCHAR(255),
director VARCHAR(255),
actors VARCHAR(255),
synopsis VARCHAR(3000),
release_date TIMESTAMP
);
CREATE TABLE Genre(
id INTEGER PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
genre VARCHAR(255)
);
CREATE TABLE MovieHasGenre(
movie_id INTEGER REFERENCES Movie (id) NOT NULL,
genre_id INTEGER REFERENCES Genre (id) NOT NULL,
PRIMARY KEY (movie_id, genre_id)
);
package edu.unsw.comp9321.jdbc;
import java.util.HashSet;
import java.util.Set;
public class GenreDTO {
public GenreDTO() {}
public GenreDTO(int id, String genre) {
super();
this.id = id;
this.genre = genre;
}
private int id;
private String genre;
private Set<MovieDTO> movies = new HashSet<MovieDTO>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public Set<MovieDTO> getMovies() {
return movies;
}
public void setMovies(Set<MovieDTO> movies) {
this.movies = movies;
}
}
package edu.unsw.comp9321.jdbc;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.OneToMany;
public class MovieDTO implements Comparable {
private int id;
private String title;
private String poster;
private String director;
private String actors;
private String synopsis;
private String release_date;
private int cinema_id;
private Set<GenreDTO> genres = new HashSet<GenreDTO>();
private Set<ReviewDTO> reviews = new HashSet<ReviewDTO>();
private double rating;
public MovieDTO() {
}
public MovieDTO(int id, String title, String poster, String director,
String actors, String synopsis, String release_date, double rating) {
super();
this.id = id;
this.title = title;
this.poster = poster;
this.director = director;
this.actors = actors;
this.synopsis = synopsis;
this.release_date = release_date;
this.rating = rating;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getActors() {
return actors;
}
public void setActors(String actors) {
this.actors = actors;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public Set<GenreDTO> getGenres() {
return genres;
}
public void setGenres(Set<GenreDTO> genres) {
this.genres = genres;
}
public Set<ReviewDTO> getReviews() {
return reviews;
}
public void setReviews(Set<ReviewDTO> reviews) {
this.reviews = reviews;
}
public int getCinema_id() {
return cinema_id;
}
public void setCinema_id(int cinema_id) {
this.cinema_id = cinema_id;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
#Override
public int compareTo(Object o) {
MovieDTO other = (MovieDTO) o;
if (this.rating > other.rating) return -1;
if (this.rating < other.rating) return 1;
return 0;
}
}

Yes. There is a better way. Just use a join:
select m from Movie m join m.genres g where g.genre like :genre
or
select m from Genre g join g.movies m where g.genre like :genre
Note that using a like clause is a bit odd. You should use the ID of the genre to uniquely identify it. And if you only have part of a genre's name, you shouldn't assume only one genre contains this genre part.
Also, a DTO is not an entity, and vice-versa. Don't name an entity GenreDTO or MovieDTO. Name it Genre or Movie.

Related

Get data from Junction Table with Android Room

I am currently building an android app, which displays a Route, which is constructed out of multiple waypoints. I already planned the database schema (chen-notation [possibly invalid "syntax"]):
I tried to recreate the n-m relation with android room, but I can't figure out how I can retrieve the index_of_route attribute of the junction table (route_waypoint).
I want the junction table attribute index_of_route, when I get the Data like so:
#Transaction
#Query("SELECT * FROM POIRoute")
List<RouteWithWaypoints> getRoutes();
inside the POIWaypoint class (maybe as extra attribute), or at least accessible from another class which maybe is implemented like so:
#Embedded
POIWaypoint waypoint;
int indexOfRoute;
Currently I don't get the indexOfRoute attribute from the junction table.
My already created classes:
RouteWithWaypoints:
public class RouteWithWaypoints {
#Embedded
private POIRoute poiRoute;
#Relation(parentColumn = "id",entityColumn = "id",associateBy = #Junction(value = RouteWaypoint.class, parentColumn = "routeId", entityColumn = "waypointId"))
private List<POIWaypoint> waypoints;
public POIRoute getPoiRoute() {
return poiRoute;
}
public void setPoiRoute(POIRoute poiRoute) {
this.poiRoute = poiRoute;
}
public List<POIWaypoint> getWaypoints() {
return waypoints;
}
public void setWaypoints(List<POIWaypoint> waypoints) {
this.waypoints = waypoints;
}
RouteWaypoint:
#Entity(primaryKeys = {"waypointId", "routeId"}, foreignKeys = {
#ForeignKey(entity = POIWaypoint.class, parentColumns = {"id"}, childColumns = {"waypointId"}),
#ForeignKey(entity = POIRoute.class, parentColumns = {"id"}, childColumns = {"routeId"})
})
public class RouteWaypoint {
private int waypointId;
private int routeId;
// I want this attribute inside the POIWaypoint class
#ColumnInfo(name = "index_of_route")
private int indexOfRoute;
public int getWaypointId() {
return waypointId;
}
public void setWaypointId(int waypointId) {
this.waypointId = waypointId;
}
public int getRouteId() {
return routeId;
}
public void setRouteId(int routeId) {
this.routeId = routeId;
}
}
POIRoute:
#Entity
public class POIRoute{
private String name;
private String description;
#PrimaryKey(autoGenerate = true)
private int id;
private boolean user_generated;
private int parentId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isUser_generated() {
return user_generated;
}
public void setUser_generated(boolean user_generated) {
this.user_generated = user_generated;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
}
POIWaypoint (please ignore the position attribute it isn't finished):
#Entity
public class POIWaypoint {
#PrimaryKey(autoGenerate = true)
private long id;
#ColumnInfo(name = "long_description")
private String longDescription;
private String title;
#ColumnInfo(name = "short_description")
private String shortDescription;
// use converter: https://developer.android.com/training/data-storage/room/referencing-data
#Ignore
private GeoPoint position;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public GeoPoint getPosition() {
return position;
}
public void setPosition(GeoPoint position) {
this.position = position;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
I solved my problem by manage the relation by myself. I changed my RouteDao to an abstract class to insert my own method, which manages part of the junction table by itself:
RouteDao:
private RouteDatabase database;
public RouteDao(RouteDatabase database) {
this.database = database;
}
#Query("Select * from POIRoute")
public abstract List<POIRoute> getRoutes();
#Query("SELECT * FROM POIRoute WHERE id = :id")
public abstract POIRoute getRoute(int id);
#Insert
abstract void insertRouteWithWaypoints(RouteWithWaypoints routeWithWaypoints);
public List<RouteWithWaypoints> getRoutesWithWaypoints() {
List<POIRoute> routes = this.getRoutes();
List<RouteWithWaypoints> routesWithWaypoints = new LinkedList<>();
for (POIRoute r : routes) {
routesWithWaypoints.add(new RouteWithWaypoints(r, database.wayPointDao().getWaypointsFromRoute(r.getId())));
}
return routesWithWaypoints;
}
public RouteWithWaypoints getRouteWithWaypoints(int id) {
POIRoute route = this.getRoute(id);
RouteWithWaypoints routeWithWaypoints = null;
if (route != null) {
routeWithWaypoints = new RouteWithWaypoints(route, database.wayPointDao().getWaypointsFromRoute(route.getId()));
}
return routeWithWaypoints;
}
WayPointDao:
#Query("SELECT * FROM POIWaypoint")
POIWaypoint getWaypoints();
#Query("SELECT * FROM POIWaypoint WHERE id = :id")
POIWaypoint getWaypoint(long id);
#Query("SELECT pw.*, rw.index_of_route as 'index' FROM POIWaypoint as pw Join RouteWaypoint as rw on (rw.waypointId = pw.id) where rw.routeId = :id order by 'index' ASC")
List<POIRouteStep> getWaypointsFromRoute(int id);

How to implement multiple primary keys in ORMLite

In my database there are many tables with double primary keys and even triples. Would I have a great request how to map such a table in ormlite in Java? For example: I have an Order and Product table, and a third table Order_Product, who join erlier mentioned two tables. In third table i have 2 master keys: order_id and product_id, and a normal field: quantity. I would be very grateful for explaining this problem (some examples). P.S. Sorry for my english.
I have read that i should use an attribute like uniqueCombo, useGetSet, but I do not know how to do it. And i don't know if i could use foreign annotation for these primary fields.
``` def class Order:
#DatabaseTable(tableName = "Orders")
public class Order{
public Order(){}
#DatabaseField(generatedId = true)
private int id;
#DatabaseField(columnName = "Date", canBeNull = false)
private Date date;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public Date getDate() { return date; }
public void setDate(Date date) { this.date = date; }
}
#DatabaseTable(tableName = "Products")
public class Product{
public Product(){}
#DatabaseField(generatedId = true)
private int id;
#DatabaseField(columnName = "Name", canBeNull = false)
private String name;
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; }
}
#DatabaseTable(tableName = "Order_Products")
public class Order_Product{
public Order_Product(){}
#DatabaseField(id = true, uniqueCombo=true)
private int order_id;
#DatabaseField(id = true, uniqueCombo=true)
private int product_id;
#DatabaseField(columnName = "Quantity", canBeNull = false)
private int quantity;
public int getOrder_id() { return order_id; }
public void setOrder_id(int order_id) { this.order_id = order_id; }
public int getProduct_id() { return product_id; }
public void setProduct_id(int product_id) { this.product_id = product_id; }
public int getQuantity() { return quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; }
}

#ElementCollection does not getting detached

My goal is to clone entity 'Product' with all its filters.
For example, I have an entity (getters and setters omitted for simplicity):
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ElementCollection()
private List<Filter> filters = new ArrayList<Filter>();
}
And embeddable class:
#Embeddable
public class Filter {
#Column(length = 255, nullable = false)
private String name;
#Column(nullable = false)
private long variant = -1;
}
Now, if I do:
entityManager.detach(product);
product.setId(null);
productService.save(product);
I will get a copy of product entity but with filters from original product. In meanwhile original product will end up with no filters at all..
Thats how filter's table rows looks like:
Before:
product_id; name; variant
217; "f2"; 86
After:
product_id; name; variant
218; "f2"; 86
I tried detach each filter from the list but it gives me error.
How can I make it copy filters with an entity?
Edit: Added full Product and Filter code:
package com.serhiy1.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.SortableField;
import org.joda.time.DateTime;
import com.serhiy1.constraint.LocalePacker;
#Indexed
#Entity
#EntityListeners(ProductListener.class)
public class Product {
public static final int PRICE_PER_ONE = 0;
public static final int PRICE_PER_METER = 1;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long code;
private String name = "";
private String grouping = "";
#Field
#Column(columnDefinition="text")
private String title = "";
#Field
#Column(columnDefinition="text")
private String intro = "";
#Column(columnDefinition="text")
private String content = "";
#Field
#Column(columnDefinition="text")
private String contentHtml = "";
private String locale = "en";
private Long parentId = 0L;
private DateTime time;
private DateTime timeMod;
private Long balanceRequired = 0L;
private Integer index = 0;
#Field(name = "price_sort")
#SortableField(forField = "price_sort")
private Double price = 0.0;
private Integer pricePer;
#Transient
private long childrenCount = 0;
#Transient
private String image = "";
#Transient
private List<String> images = new ArrayList<String>();
#ManyToOne(targetEntity = User.class)
#JoinColumn(nullable = false, name = "user_id")
#LazyCollection(LazyCollectionOption.FALSE)
private User user;
#ManyToOne(targetEntity = Product.class)
#JoinColumn(nullable = true, name = "category_id")
#LazyCollection(LazyCollectionOption.FALSE)
private Product category;
#ElementCollection()
private List<Filter> filters = new ArrayList<Filter>();
#ElementCollection()
private List<Modifier> modifiers = new ArrayList<Modifier>();
public Product() {
}
#Transient
private String _title = "";
#Transient
private String _intro = "";
#Transient
private String _content = "";
#Transient
private String _contentHtml = "";
public void pack(String locale, List<String> locales) {
if(locale.contains("_")) return;
title = LocalePacker.repack(locale, _title, title, locales);
intro = LocalePacker.repack(locale, _intro, intro, locales);
content = LocalePacker.repack(locale, _content, content, locales);
contentHtml = LocalePacker.repack(locale, _contentHtml, contentHtml, locales);
}
public void unpack(String locale) {
_title = LocalePacker.unpackStr(locale, title).getOrDefault(locale, "");
_intro = LocalePacker.unpackStr(locale, intro).getOrDefault(locale, "");
_content = LocalePacker.unpackStr(locale, content).getOrDefault(locale, "");
_contentHtml = LocalePacker.unpackStr(locale, contentHtml).getOrDefault(locale, "");
}
public void copy(String landFrom, String landTo) {
title = LocalePacker.copyLang(title, landFrom, landTo);
intro = LocalePacker.copyLang(intro, landFrom, landTo);
content = LocalePacker.copyLang(content, landFrom, landTo);
contentHtml = LocalePacker.copyLang(contentHtml, landFrom, landTo);
}
public Modifier getModifier(String name) {
for(Modifier m: modifiers) {
if(m.getName().equals(name)) return m;
}
return null;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getCode() {
return code == null ? id : code;
}
public void setCode(long code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrouping() {
return grouping;
}
public void setGrouping(String grouping) {
this.grouping = grouping;
}
public String getTitle() {
return _title;
}
public void setTitle(String title) {
this._title = title;
}
public String getIntro() {
return _intro;
}
public void setIntro(String intro) {
this._intro = intro;
}
public String getContent() {
return _content;
}
public void setContent(String content) {
this._content = content;
}
public String getContentHtml() {
return _contentHtml;
}
public void setContentHtml(String contentHtml) {
this._contentHtml = contentHtml;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public long getParentId() {
return parentId;
}
public void setParentId(long parentId) {
this.parentId = parentId;
}
public DateTime getTime() {
return time;
}
public void setTime(DateTime time) {
this.time = time;
}
public DateTime getTimeMod() {
return timeMod;
}
public void setTimeMod(DateTime timeMod) {
this.timeMod = timeMod;
}
public long getBalanceRequired() {
return balanceRequired == null ? 0L : balanceRequired;
}
public void setBalanceRequired(long balanceRequired) {
this.balanceRequired = balanceRequired;
}
public Integer getIndex() {
//return index == null ? 1000 : index;
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public double getPrice() {
return price == null ? 0.0 : price;
}
public void setPrice(double price) {
this.price = price;
}
public int getPricePer() {
return pricePer == null ? PRICE_PER_METER : pricePer;
}
public void setPricePer(int pricePer) {
this.pricePer = pricePer;
}
public long getChildrenCount() {
return childrenCount;
}
public void setChildrenCount(long childrenCount) {
this.childrenCount = childrenCount;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Product getCategory() {
return category;
}
public void setCategory(Product category) {
this.category = category;
}
public List<Filter> getFilters() {
return filters;
}
public void setFilters(List<Filter> filters) {
this.filters = filters;
}
public List<Modifier> getModifiers() {
return modifiers;
}
public void setModifiers(List<Modifier> modifiers) {
this.modifiers = modifiers;
}
public boolean isCategory() { return price < 0; }
#Override
public String toString() {
return "Article{" +
"id=" + id +
'}';
}
}
..
package com.serhiy1.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Transient;
#Embeddable
public class Filter {
#Column(length = 255, nullable = false)
private String name;
#Column(nullable = false)
private long variant = -1;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getVariant() {
return variant;
}
public void setVariant(long variant) {
this.variant = variant;
}
}
I made a mini project trying to replicate your issue.
It is a String Boot project with H2 database and JPA (Hibernate implementation).
On startup, Hibernate creates 2 tables:
create table product (
id bigint not null,
primary key (id)
)
and
create table product_filters (
product_id bigint not null,
name varchar(255) not null,
variant bigint not null
)
On product with filters creation, both tables get inserted:
insert
into
product
(id)
values
(1)
and
insert
into
product_filters
(product_id, name, variant)
values
(1, "f1", 1)
After:
entityManager.detach(product);
product.setId(null);
productService.save(product);
Hibernate issues:
delete
from
product_filters
where
product_id=1
which is normal, since filters is an ElementCollection therefore it is totally owned by the entity Product. On productService.save(product) Hibernate detects that filters collection is bound to another Product therefore deletes the old bound (from product_filter table) before creating a new one.
The only way to overcome the deletion is to recreate the collection:
List<Filter> filters = new ArrayList<Filter>();
filters.addAll(oldFilters);
product.setFilters(filters);
To sum up, here is the solution:
// To trigger the fetch
List<Filter> filters = new ArrayList<Filter>(product.getFilters());
entityManager.detach(product);
product.setId(null);
product.setFilters(filters);
productService.save(product);

How to add a mongo id from one collection as a foreign key in another collection

In my Spring boot application, I have collection of Todos and a collection of Courses. In the view of the application, I return the collection of courses and display whatever course I need. The Todos are stored as 1 list which represents all the current Todos. What I would like to do is return a list of Todos for each course. So when the view is opened, the application would display the the course plus the individual todo list for that course.
Is there a way I can use the existing code to incorporate the new functionality. I have created the front end logic and would like to keep that. My initial idea was to add the the course id to the Todo.java, but that did not work.
Todo.java
#Document(collection="todos")
public class Todo {
#Id
private String id;
#NotBlank
#Size(max=250)
#Indexed(unique=true)
private String title;
private Boolean completed = false;
private Date createdAt = new Date();
public Todo() {
super();
}
public Todo(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return String.format(
"Todo[id=%s, title='%s', completed='%s']",
id, title, completed);
}
}
TodoRepository.java
#Repository
public interface TodoRepository extends MongoRepository<Todo, String> {
public List<Todo> findAll();
public Todo findOne(String id);
public Todo save(Todo todo);
public void delete(Todo todo);
}
Courses
#Document(collection = "courses")
public class Courses {
#Id
private String id;
private String name;
private String lecturer;
private String picture;
private String video;
private String description;
private String enroled;
public Courses(){}
public Courses(String name, String lecturer, String picture, String video, String description,String enroled) {
this.name = name;
this.lecturer = lecturer;
this.picture = picture;
this.video = video;
this.description = description;
this.enroled = enroled;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLecturer() {
return lecturer;
}
public void setLecturer(String lecturer) {
this.lecturer = lecturer;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnroled() {
return enroled;
}
public void setEnroled(String enroled) {
this.enroled = enroled;
}
#Override
public String toString() {
return "Courses{" +
"id='" + id + "'" +
", name='" + name + "'" +
", lecturer='" + lecturer + "'" +
", description='" + description + "'" +
'}';
}
}

How to remove data from Arraylist by data id

I am having problem in removing data from my arraylist by its id.
I have a books in my arraylist and i want to remove a particular books based on its id.
I tried the below code but my data is not removing.
Please check my code below and suggest a solution for it.
Update
When i calls this method then compiler reads all the below code but it does not removes my data from my arraylist. I am not getting any error.
-------------------
-------------------
public String removebookfrmSession()
{
List<Bookdetails> books = new ArrayList<Bookdetails>();
String bookid = request.getParameter("bkid");
Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
books = (ArrayList) session.get(BillTransactionBooksConstants.BOK);
if ( books == null ) books = new ArrayList<Bookdetails>();
boolean already_exists = false;
for ( Bookdetails b : books )
{
if ( Integer.toString(b.getId()).equals(bookid))
{
already_exists = true;
break;
}
}
if (book != null && already_exists )
{
books.remove(book);
System.out.println("books size"+books.size());
session.put(BillTransactionBooksConstants.BOK,books);
}
return SUCCESS;
}
Bookdetails.java (POJO)
package v.esoft.pojos;
// Generated Nov 5, 2012 9:37:14 PM by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Bookdetails generated by hbm2java
*/
#Entity
#Table(name = "bookdetails", catalog = "vbsoftware")
public class Bookdetails implements java.io.Serializable {
private Integer id;
private String isbn;
private String bookTitile;
private String authFirstname;
private String authLastname;
private String editionYear;
private Integer subjectId;
private Integer coverId;
private Integer languageId;
private String publisherName;
private Integer editionId;
private Float price;
private String quantity;
private String description;
private Integer locationId;
private String remarks;
private String img1;
private String img2;
private String videoUrl;
private Integer createrId;
private Date createdDate;
private Integer updateId;
private Date updatedDate;
public Bookdetails() {
}
public Bookdetails(String isbn, String bookTitile, String authFirstname,
String authLastname, String editionYear, Integer subjectId,
Integer coverId, Integer languageId, String publisherName,
Integer editionId, Float price, String quantity,
String description, Integer locationId, String remarks,
String img1, String img2, String videoUrl, Integer createrId,
Date createdDate, Integer updateId, Date updatedDate) {
this.isbn = isbn;
this.bookTitile = bookTitile;
this.authFirstname = authFirstname;
this.authLastname = authLastname;
this.editionYear = editionYear;
this.subjectId = subjectId;
this.coverId = coverId;
this.languageId = languageId;
this.publisherName = publisherName;
this.editionId = editionId;
this.price = price;
this.quantity = quantity;
this.description = description;
this.locationId = locationId;
this.remarks = remarks;
this.img1 = img1;
this.img2 = img2;
this.videoUrl = videoUrl;
this.createrId = createrId;
this.createdDate = createdDate;
this.updateId = updateId;
this.updatedDate = updatedDate;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "isbn", length = 90)
public String getIsbn() {
return this.isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
#Column(name = "book_titile")
public String getBookTitile() {
return this.bookTitile;
}
public void setBookTitile(String bookTitile) {
this.bookTitile = bookTitile;
}
#Column(name = "auth_firstname", length = 120)
public String getAuthFirstname() {
return this.authFirstname;
}
public void setAuthFirstname(String authFirstname) {
this.authFirstname = authFirstname;
}
#Column(name = "auth_lastname", length = 120)
public String getAuthLastname() {
return this.authLastname;
}
public void setAuthLastname(String authLastname) {
this.authLastname = authLastname;
}
#Column(name = "edition_year", length = 20)
public String getEditionYear() {
return this.editionYear;
}
public void setEditionYear(String editionYear) {
this.editionYear = editionYear;
}
#Column(name = "subject_id")
public Integer getSubjectId() {
return this.subjectId;
}
public void setSubjectId(Integer subjectId) {
this.subjectId = subjectId;
}
#Column(name = "cover_id")
public Integer getCoverId() {
return this.coverId;
}
public void setCoverId(Integer coverId) {
this.coverId = coverId;
}
#Column(name = "language_id")
public Integer getLanguageId() {
return this.languageId;
}
public void setLanguageId(Integer languageId) {
this.languageId = languageId;
}
#Column(name = "publisher_name", length = 70)
public String getPublisherName() {
return this.publisherName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
#Column(name = "edition_id")
public Integer getEditionId() {
return this.editionId;
}
public void setEditionId(Integer editionId) {
this.editionId = editionId;
}
#Column(name = "price", precision = 12, scale = 0)
public Float getPrice() {
return this.price;
}
public void setPrice(Float price) {
this.price = price;
}
#Column(name = "quantity", length = 40)
public String getQuantity() {
return this.quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
#Column(name = "description", length = 65535)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "location_id")
public Integer getLocationId() {
return this.locationId;
}
public void setLocationId(Integer locationId) {
this.locationId = locationId;
}
#Column(name = "remarks", length = 65535)
public String getRemarks() {
return this.remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
#Column(name = "img1")
public String getImg1() {
return this.img1;
}
public void setImg1(String img1) {
this.img1 = img1;
}
#Column(name = "img2")
public String getImg2() {
return this.img2;
}
public void setImg2(String img2) {
this.img2 = img2;
}
#Column(name = "video_url", length = 65535)
public String getVideoUrl() {
return this.videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
#Column(name = "creater_id")
public Integer getCreaterId() {
return this.createrId;
}
public void setCreaterId(Integer createrId) {
this.createrId = createrId;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_date", length = 19)
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
#Column(name = "update_id")
public Integer getUpdateId() {
return this.updateId;
}
public void setUpdateId(Integer updateId) {
this.updateId = updateId;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated_date", length = 19)
public Date getUpdatedDate() {
return this.updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
}
Your Bookdetails class must implement the public boolean equals(Object o) method in order to use the List#remove(Object o) method. Otherwise, you should handle the object removal by yourself as stated by #juergend.
Implementing the equals method would be like this:
public class Bookdetails {
private int id;
//other attributes and methods...
#Override
public boolean equals(Object o) {
if (o instanceof Bookdetails) {
Bookdetails oBookdetails = (Bookdetails)o;
return (this.id == oBookdetails.id);
}
return false;
}
}
Now the books.remove(book); would work without need of the for ( Bookdetails b : books ) loop.
Default equality is based on reference so you need to assign book to reference from the list so that remove will work. Or you can override equals but I am not quite sure whether you can provide equality on bookId
for ( Bookdetails b : books )
{
if ( Integer.toString(b.getId()).equals(bookid))
{
already_exists = true;
book= b;
break;
}
}
Then when you call remove because of reference equality it will remove book
Update:
If its POJO and you have primary key then you can easily implement equals on primary key that is id. No need to iterate over the list.

Categories