I want to make a table, let's say table's name is Car. It will has 3 column, brandId, typeId and sizeId. I want all of the columns to be primary key. typeId and sizeId are column from different table. I already try to make code using #IdClass. But, error "No supertype found" appear.
This is Entity clas :
#Entity
#IdClass(CarPk.class)
#Table(name = "CAR")
public class Car implements Serializable {
private static final long serialVersionUID = -1576946068763487642L;
public Car() {
}
public Car(String brandId, TypeId typeId, SizeId sizeId) {
this.brandId = brandId;
this.typeId = typeId;
this.sizeId = sizeId;
}
#Id
#Column(name = "BRAND_ID", nullable = false, length = 20)
private String brandId;
#Id
#ManyToOne
#JoinColumn(name = "TYPE_ID", nullable = false)
private TypeId typeId;
#Id
#ManyToOne
#JoinColumn(name = "SIZE_ID", nullable = false)
private SizeId sizeId;
public String getBrandId() {
return brandId;
}
public void setBrandId(String brandId) {
this.brandId= brandId;
}
public TypeId getTypeId() {
return typeId;
}
public void setTypeId (TypeId typeId) {
this.typeId= typeId;
}
public SizeId getSizeId() {
return sizeId;
}
public void setSizeId (SizeId sizeId) {
this.sizeId= sizeId;
}
}
And this is CarPk class :
public class CarPk implements Serializable {
private static final long serialVersionUID = -1576946068763487642L;
public CarPk() {
}
public CarPk(String brandId, TypeId typeId, SizeId sizeId) {
this.brandId = brandId;
this.typeId = typeId;
this.sizeId = sizeId;
}
private String brandId;
private TypeId typeId;
private SizeId sizeId;
public String getBrandId() {
return brandId;
}
public void setBrandId(String brandId) {
this.brandId= brandId;
}
public TypeId getTypeId() {
return typeId;
}
public void setTypeId (TypeId typeId) {
this.typeId= typeId;
}
public SizeId getSizeId() {
return sizeId;
}
public void setSizeId (SizeId sizeId) {
this.sizeId= sizeId;
}
}
What is wrong this code?
Thank you anyway
Related
These are my model classes:
Film.java
#Entity
public class Film {
private Integer id;
private String title;
private List<FilmActor> filmActors;
#OneToMany(mappedBy = "film")
public List<FilmActor> getFilmActors() {
return filmActors;
}
public void setFilmActors(List<FilmActor> filmActors) {
this.filmActors = filmActors;
}
}
Actor.java
#Entity
public class Actor {
private Integer id;
private String firstname;
private String lastname;
private List<FilmActor> filmActors;
#OneToMany(mappedBy = "actor")
public List<FilmActor> getFilmActors() {
return filmActors;
}
public void setFilmActors(List<FilmActor> filmActors) {
this.filmActors = filmActors;
}
}
And this is the Join Table Entity:
#Entity
#Table(name = "film_actor")
public class FilmActor {
private FilmActorPK id;
private Film film;
private Actor actor;
private Timestamp lastUpdate;
#EmbeddedId
public FilmActorPK getId() {
return id;
}
public void setId(FilmActorPK id) {
this.id = id;
}
#ManyToOne
#MapsId("film")
#JoinColumn(name = "film_id")
public Film getFilm() {
return film;
}
public void setFilm(Film film) {
this.film = film;
}
#ManyToOne
#MapsId("actor")
#JoinColumn(name = "actor_id")
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
#Column(name = "last_update")
public Timestamp getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Timestamp lastUpdate) {
this.lastUpdate = lastUpdate;
}
}
and the Primary Key class:
#Embeddable
public class FilmActorPK implements Serializable {
private int actorId;
private int filmId;
#Column(name = "actor_id")
public int getActorId() {
return actorId;
}
public void setActorId(int actorId) {
this.actorId = actorId;
}
#Column(name = "film_id")
public int getFilmId() {
return filmId;
}
public void setFilmId(int filmId) {
this.filmId = filmId;
}
}
So I want to find films where 2 given actors acts. This is what I have:
#Override
public Collection<Film> filmsActorsTogether(Actor a, Actor b) {
final List<Film> filmsOfActorA = filmsOfActor(a);
final List<Film> filmsOfActorB = filmsOfActor(b);
final Collection<Film> intersection = CollectionUtils.intersection(filmsOfActorA, filmsOfActorB);
return intersection;
}
#Override
public List<Film> filmsOfActor(Actor actor) {
final EntityManager entityManager = persistenceUtil.getEntityManager();
final Actor persistentActor = entityManager.find(Actor.class, actor.getId());
final ArrayList<Film> films = new ArrayList<Film>();
for (FilmActor filmActor : persistentActor.getFilmActors()) {
films.add(filmActor.getFilm());
}
entityManager.close();
return films;
}
Is there any way to achieve this without fetching ALL films of 2 actors, and using filtering in memory? How do I get the Films directly from the DB with JQL?
Maybe there is something more elegant, but the following query should work:
select f from Film f where
(select count(fa.id) from FilmActor fa
where fa.film = f
and (fa.actor = :actor1 or fa.actor = :actor2)) = 2
Side note: your PK class should have a correct equals() and hashCode() methods
This is it my database project:
I have a problem with the correct combination of tables, as it is in the picture.
This is my files:
Category.java
#Entity
public class Category {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String categoryName;
protected Category() {}
public Category(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryName() {
return categoryName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
#Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s']",
id, categoryName);
}
}
Items.java
#Entity
#Table(name = "Items")
public class Items {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int ItemId;
private String ItemName;
private String price;
private Set<Locals> locals = new HashSet<Locals>(0);
public Items(){
}
public Items(String price, String itemName) {
this.price = price;
this.ItemName = itemName;
}
public void setItemId(int itemId) {
ItemId = itemId;
}
public void setLocals(Set<Locals> locals) {
this.locals = locals;
}
public void setPrice(String price) {
this.price = price;
}
public void setItemName(String itemName) {
ItemName = itemName;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ItemId", unique = true, nullable = false)
public int getItemId() {
return ItemId;
}
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "itemsTo")
public Set<Locals> getLocals() {
return locals;
}
#Column(name = "price", nullable = false, length = 10)
public String getPrice() {
return price;
}
#Column(name = "ItemName", nullable = false, length = 10)
public String getItemName() {
return ItemName;
}
}
Locals.java
#Entity
#Table(name = "Locals")
public class Locals {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int LocalId;
private String localName;
private String address;
private String phoneNumber;
private String coorX;
private String coorY;
private Set<Items> itemsTo = new HashSet<Items>(0);
public Locals(){
}
public Locals(String localName,String address,String phoneNumber, String coorY, String coorX) {
this.coorY = coorY;
this.coorX = coorX;
this.phoneNumber = phoneNumber;
this.address = address;
this.localName = localName;
}
public Locals(String localName,String address,String phoneNumber, String coorY, String coorX, Set<Items> itemsTo) {
this.coorY = coorY;
this.coorX = coorX;
this.phoneNumber = phoneNumber;
this.address = address;
this.localName = localName;
this.itemsTo = itemsTo;
}
public void setLocalId(int localId) {
LocalId = localId;
}
public void setLocalName(String localName) {
this.localName = localName;
}
public void setAddress(String address) {
this.address = address;
}
public void setCoorX(String coorX) {
this.coorX = coorX;
}
public void setCoorY(String coorY) {
this.coorY = coorY;
}
public void setItemsTo(Set<Items> itemsTo) {
this.itemsTo = itemsTo;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "LocalId", unique = true, nullable = false)
public int getLocalId() {
return LocalId;
}
#Column(name = "localName", unique = false, nullable = false, length = 10)
public String getLocalName() {
return localName;
}
#Column(name = "address", unique = false, nullable = false, length = 10)
public String getAddress() {
return address;
}
#Column(name = "phoneNumber", unique = false, nullable = false, length = 10)
public String getPhoneNumber() {
return phoneNumber;
}
#Column(name = "coorX", unique = false, nullable = false, length = 10)
public String getCoorX() {
return coorX;
}
#Column(name = "coorY", unique = false, nullable = false, length = 10)
public String getCoorY() {
return coorY;
}
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "ItemsFinall", joinColumns = {
#JoinColumn(name = "LocalId", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "ItemId",
nullable = false, updatable = false) })
public Set<Items> getItemsTo() {
return itemsTo;
}
}
and ItemsFinall.java
#Entity
#Table(name = "ItemsFinall")
public class ItemsFinall {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private int ItemId;
private int CategoryId;
private int LocalId;
public ItemsFinall(int id, int localId, int categoryId, int itemId) {
this.LocalId = localId;
this.CategoryId = categoryId;
this.ItemId = itemId;
this.id=id;
}
public void setId(int id) {
this.id = id;
}
public void setLocalId(int localId) {
LocalId = localId;
}
public void setCategoryId(int categoryId) {
CategoryId = categoryId;
}
public void setItemId(int itemId) {
ItemId = itemId;
}
public int getLocalId() {
return LocalId;
}
public int getCategoryId() {
return CategoryId;
}
public int getItemId() {
return ItemId;
}
public int getId() {
return id;
}
}
I get the following error: Caused by: org.springframework.data.mapping.PropertyReferenceException: No property categoryName found for type ItemsFinall!
I do not know what to do to properly connect the table.
ItemsServiceImpl.java
package dnfserver.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Łukasz on 2015-03-14.
*/
#Component
public class CategoryServiceImpl implements CategoryService {
#Autowired
private CategoryRepository categoryRepository;
private Map<Integer,String> categoryMap = new HashMap<Integer, String>();
#Override
public Category create(Category category) {
Category createdCategory = category;
return categoryRepository.save(createdCategory);
}
#Override
public Category delete(int id) {
return null;
}
#Autowired
public Map<Integer,String> findAll(){
int i=0;
for (Category cat : categoryRepository.findAll()) {
categoryMap.put(i,cat.toString());
i++;
}
return categoryMap;
}
#Override
public Category update(Category shop) {
return null;
}
#Override
public Category findById(int id) {
return categoryRepository.findOne(id);
}
}
In hibernate/JPA you model the relationship between Entities, but not use plain Ids!
For example
#Entity
#Table(name = "ItemsFinall")
public class ItemsFinall {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
//instead of: private int ItemId;
#OneToMany
private Item item;
//instead of: private int CategoryId;
#OneToMany
private Category category;
//instead of: private int LocalId;
#OneToMany
private Local local;
...
(You also need to fix the Set<Locals> locals in item)
I have a rest server and client which uses this API. I have a list of hotels and it had passed well until I added bidirectional dependencies to other entities.After that I start receive an endless array of entities which just repeat the same row in database.
It is my first project with hibernate so may be I made trivial mistakes of novice.
Hotel:
#Entity
#Table(name = "hotels", schema = "", catalog = "mydb")
public class HotelsEntity implements HospitalityEntity{
private int idHotel;
private String name;
private String region;
private String description;
// private byte[] photo;
private HotelPropertyEntity property;
private List<RoomEntity> rooms;
#OneToOne(mappedBy = "hotel")
public HotelPropertyEntity getProperty() {
return property;
}
public void setProperty(HotelPropertyEntity property) {
this.property = property;
}
#OneToMany(mappedBy = "hotel")
public List<RoomEntity> getRooms() {
return rooms;
}
public void setRooms(List<RoomEntity> rooms) {
this.rooms = rooms;
}
#Id
#Column(name = "id_hotel", unique = true)
#GeneratedValue(strategy=GenerationType.AUTO)
public int getIdHotel() {
return idHotel;
}
public void setIdHotel(int idHotel) {
this.idHotel = idHotel;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "region")
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
#Basic
#Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
HotelProperty
#Entity
#Table(name = "hotel_property", schema = "", catalog = "mydb")
public class HotelPropertyEntity {
private int idHotelProperty;
private byte hasPool;
private byte hasTennisCourt;
private byte hasWaterslides;
private HotelsEntity hotel;
#Id
#Column(name = "id_hotel_property", unique = true)
#GeneratedValue(strategy=GenerationType.AUTO)
public int getIdHotelProperty() {
return idHotelProperty;
}
public void setIdHotelProperty(int idHotelProperty) {
this.idHotelProperty = idHotelProperty;
}
#Basic
#Column(name = "has_pool", columnDefinition = "BIT", length = 1)
public byte getHasPool() {
return hasPool;
}
public void setHasPool(byte hasPool) {
this.hasPool = hasPool;
}
#Basic
#Column(name = "has_tennis_court", columnDefinition = "BIT", length = 1)
public byte getHasTennisCourt() {
return hasTennisCourt;
}
public void setHasTennisCourt(byte hasTennisCourt) {
this.hasTennisCourt = hasTennisCourt;
}
#Basic
#Column(name = "has_waterslides", columnDefinition = "BIT", length = 1)
public byte getHasWaterslides() {
return hasWaterslides;
}
public void setHasWaterslides(byte hasWaterslides) {
this.hasWaterslides = hasWaterslides;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_hotel_property")
public HotelsEntity getHotel() {
return hotel;
}
public void setHotel(HotelsEntity hotel) {
this.hotel = hotel;
}
Room:
#Entity
#Table(name = "room", schema = "", catalog = "mydb")
public class RoomEntity {
private int idRoom;
private String roomType;
private int peopleCapacity;
private Boolean booked;
private Boolean locked;
private HotelsEntity hotel;
private InventoriesEntity inventory;
private RoomPropertyEntity roomProperty;
#OneToOne(mappedBy = "room")
public RoomPropertyEntity getRoom() {
return roomProperty;
}
public void setRoom(RoomPropertyEntity roomProperty) {
this.roomProperty = roomProperty;
}
#OneToOne
#JoinColumn(name = "id_room")
public InventoriesEntity getInventory() {
return inventory;
}
public void setInventory(InventoriesEntity inventory) {
this.inventory = inventory;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_hotel")
public HotelsEntity getHotel() {
return hotel;
}
public void setHotel(HotelsEntity hotel) {
this.hotel = hotel;
}
#Id
#Column(name = "id_room")
public int getIdRoom() {
return idRoom;
}
public void setIdRoom(int idRoom) {
this.idRoom = idRoom;
}
#Basic
#Column(name = "room_type")
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
#Basic
#Column(name = "people_capacity")
public int getPeopleCapacity() {
return peopleCapacity;
}
public void setPeopleCapacity(int peopleCapacity) {
this.peopleCapacity = peopleCapacity;
}
#Basic
#Column(name = "booked", columnDefinition = "BIT", length = 1)
public Boolean getBooked() {
return booked;
}
public void setBooked(Boolean booked) {
this.booked = booked;
}
#Basic
#Column(name = "locked", columnDefinition = "BIT", length = 1)
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
Could you please advise what is a way or ways to tell hibernate to stop this cycle?
p.s
This code contains another one issue. I f I remove one to one dependency and remain only one to many I receive failed to lazily initialize a collection of role: com.example.model.HotelsEntity.rooms, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.example.model.HotelsEntity["rooms"])
You need to mark entity as not serializable for JSON. Please use #JsonIgnore or #JsonIgnoreProperties("field") on one of the sides of the relations (the annotation is class-level).
I use Hibernate and
have two entities(City and Region) with OneToMany relation.
the First:
#Entity
#Table(name = "p_region")
public class Region implements Serializable{
#OneToMany(mappedBy = "region",fetch= FetchType.LAZY, cascade = CascadeType.MERGE)
private List<City> citys;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
//++++++++++++++++++++ GETSET
public List<City> getCitys() {
return citys;
}
public void setCitys(List<City> citys) {
this.citys = citys;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and the second one:
#Entity
#Table(name = "p_city")
public class City implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotEmpty(message = "Название не должно быть пустым")
#Length(max = 10, min = 2, message = "Название должно быть менее 2 символов и не
более 100")
private String cityName;
#NotEmpty(message = "Код города не должно быть пустым")
private String cityCode;
#Column(name = "zone")
private Integer zone;
#Basic(optional = true)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date entryDate = Calendar.getInstance().getTime();
#ManyToOne()
private Region region;
#Basic(optional = true)
private String zip_code;
// GET SET ::::::::::::::::::::::::::::::::::
public Integer getZone() {
return zone;
}
public void setZone(Integer zone) {
this.zone = zone;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public void delete() {
System.out.println("QQQQQQQQQQQQQQQQQQQQQQ");
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Date getEntryDate() {
return entryDate;
}
public void setEntryDate(Date entryDate) {
this.entryDate = entryDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getZip_code() {
return zip_code;
}
public void setZip_code(String zip_code) {
this.zip_code = zip_code;
}
}
When I try to get simple Object(City) with JSON it returns the cycle:
{"id":577,"region":{"name":"нет региона","id":15,"citys":[{"id":577,"region":
{"name":"нет региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет......so on.
Are there any solutions for this issue?
You need to break the bi-directional relationship between your entity before converting to JSON.
I think there are two options:
Iterate the child collection, e.g. citys in Region and set Region to null. This way, circular dependency would be broken. You my want to add one name mapped attribute regionId in the City so that relational info is still available.
Create another set of POJO objects without circular dependency, copy the values from Entity Objects and then get the JSON using POJO objects.
I am modeling a database.
There is TRIPLE which contains three CONCEPT. So the primary key of the class TRIPLE is three uri all together. (One concept could be in different TRIPLE).
Also TRIPLE is related with another class, ANNOTATION, and here is the question, how can triple_id be identified?? But first of all, if building this Id composite is correct.
To model that:
Concept.java
#Entity
#Table(name = "concept")
public class Concept implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String id;
private List<TripleDBModel> triples;
#ManyToMany(
cascade={CascadeType.ALL},
fetch=FetchType.LAZY,
mappedBy = "concepts"
)
public List<TripleDBModel> getTriples() {
return triples;
}
public void setTriples(List<TripleDBModel> triples) {
this.triples = triples;
}
ConceptPk.java
#Embeddable
public class ConceptPk implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String uri;
public ConceptPk(String uri, String label){
this.uri = uri;
}
public ConceptPk(){
super();
}
#Id
#Column(name = "uri", length = 100, unique = true, nullable = false)
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
Triple.java
#Entity
#IdClass(ConceptPk.class)
#Table(name = "triple")
public class TripleDBModel {
protected List<Annotation> annotations;
protected String conceptUriSubject;
protected String conceptUriObject;
protected String conceptUriPredicate;
#ManyToMany(
cascade={CascadeType.ALL},
fetch=FetchType.LAZY
)
#JoinTable(name = "triple_has_concept",
joinColumns=#JoinColumn(name="uri"),
inverseJoinColumns=#JoinColumn(name="triple_id")) //What shoul I write here???
public List<Annotation> getAnnotations() {
return annotations;
}
public void setAnnotations(List<Annotation> annotations) {
this.annotations = annotations;
}
#Id public String getConceptUriSubject() {
return conceptUriSubject;
}
public void setConceptUriSubject(String conceptUriSubject) {
this.conceptUriSubject = conceptUriSubject;
}
#Id public String getConceptUriObject() {
return conceptUriObject;
}
public void setConceptUriObject(String conceptUriObject) {
this.conceptUriObject = conceptUriObject;
}
#Id public String getConceptUriPredicate() {
return conceptUriPredicate;
}
public void setConceptUriPredicate(String conceptUriPredicate) {
this.conceptUriPredicate = conceptUriPredicate;
}
}
Thanks in advance!!
You could use an Id class like this:
class TripleId implements Serializable {
#Column(...)
private String conceptUriSubject;
#Column(...)
private String conceptUriObject;
}
And use it in Triple:
#Entity
#Table(name = "triple")
public class TripleDBModel {
#EmbeddedId
private TripleId id;
...
}
Also note that you can provide multiple join columns:
inverseJoinColumns= {#JoinColumn(name="subjectUri"), #JoinColumn(name="objectUri"), ... }