I have a class:
#Data
#Entity
public class NewOrder {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "Id")
private int Id;
private Date createdAt = new Date();
private Type types;
public enum Type {
ONDELIVERY, INADVANCE
}
#ManyToMany
private List<Product> products = new ArrayList<>();
public void addProduct(Product product) {
this.products.add(product);
}
}
I want to show available enum values of Type in React form. How could I get them? Is it possible without creating a new class with its own controller?
Related
I'm using hibernate with manyToMany relation and I want to display data from database
Thank you in advance.
I get this errors:
database :
Here is the code :
Class EnseignerId :
#Embeddable
public class EnseignerId implements Serializable {
//id professeur
#Column(name="professeur_code")
private int code;
//id matiere
#Column(name="matiere_reference")
private String reference;
public EnseignerId() {
super();
}
//getters and setters...
Class Enseigner :
#Entity
#Table(name="Enseigner")
public class Enseigner {
#EmbeddedId
private EnseignerId id = new EnseignerId();
//id prof
#ManyToOne
#MapsId("code")
private Professeur professeur;
//id matiere
#ManyToOne
#MapsId("reference")
private Matiere matiere;
#Column(name="heures")
private int heures;
//constructor getters and setters...
Class Professeur:
#Entity
#Table(name="professeur")
public class Professeur {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="code")
private int code ;
#Column(name="nom")
private String nom;
#Column(name="prenom")
private String prenom;
...
#OneToMany(
mappedBy="professeur",
cascade = CascadeType.ALL,
orphanRemoval = true)
private List<Enseigner> matieres; //List<Association> Class; //I followed a tutorial
//constructor getters and setters...
public List<Enseigner> getMatieres() {
return matieres;
}
Class Matiere :
#Entity
#Table(name="matiere")
public class Matiere {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="reference")
private String reference;
#Column(name="description")
String description;
#Column(name="volume")
int volume;
#OneToMany(
mappedBy= "matiere",
cascade = CascadeType.ALL,
orphanRemoval = true)
private List<Enseigner> professeurs;
//constructor getters and setters...
getProfesseur() method :
public Professeur getProfesseur(int code) {
SessionFactory sessionFactory = getSessionFactory(); //static method
Session session = sessionFactory.openSession();
Professeur professeur = null;
try {
session.getTransaction().begin();
System.out.println("------------Calling getProfesseur()----------");
professeur = session.get(Professeur.class, code);
if(professeur != null) {
System.out.println(professeur);
}else {
throw new DAOException( "CODE INVALIDE!" );
}
}
catch(Exception e ) {
System.out.println(e.getMessage());
}
finally {
session.close();
}
return professeur;
}
Saving data and getting professors who don't have an Matiere work. but getting Matiere or professeur whose primary key exists in the join table Enseigner generate errors when I do something like :
Professeur prof =profDAO.getProfesseur(2); //*generates errors* //the professor with id=2 exists in database
System.out.println(prof);
List<Enseigner> enseigner = prof.getMatieres(); //*generates errors*...
List<Matiere> matieres = new ArrayList<>();
for(Enseigner ens : enseigner) {
matieres.add(ens.getMatiere());
System.out.println(ens);
}
/*for(Matiere mat : matieres) {
System.out.println(mat);
}*/
This problem has nothing to do with Hibernate. Please inspect the stack trace carefully: your Enseigner.toString() calls Professeur.toString() which in turn calls Enseigner.toString() again and so on.
I notice this problem more and more these days when people blindly use Lombok with its #Data (which should almost never be used), #ToString and #EqualsAndHashCode. These generate respective methods that include all fields!
You need to remove these annotations or set them up so that they use only the fields that you really need. Most of the time your equals() and hashCode() are not needed when you write web apps with ORM. Hibernate ensures you don't have 2 instances of the same entity.
On the other hand toString() can be useful, but we shouldn't include all fields in it - just the ones that are helpful in identifying the entity.
You have cyclic reference. You need exclude field professeurs and matieres by #JsonIgnoreProperties
I am trying to have a bi-directional relationship between the child(ZonePoint_DTO) and parent(ZoneDTO), where the parent has a composite key.
The current mapping is resulting in nulls being entered in the child(ZonePoint_DTO) table when I try to enter a whole parent object(ZoneDTO) with a list of child(ZonePoint_DTO) entities. Please note the I have set cascade type to Cascade.PERSIST.
I am using JpaRepository.save() to save Parent(ZoneDTO)
Below are the entity classes.
#Entity
#Getter
#Setter
public class ZoneDTO implements GenericPJM<ZoneDTO_Id>, Persistable<ZoneDTO_Id> {
private static Set<String> zoneNamesList;
#EmbeddedId private ZoneDTO_Id id;
private Integer noOfPolygons;
#OneToMany(mappedBy = "zoneDTO", fetch = FetchType.EAGER)
#Cascade(value = org.hibernate.annotations.CascadeType.PERSIST)
private List<ZonePointDTO> zonePointsList;
#Override
public boolean isNew() {
boolean result = !zoneNamesList.contains(id.getZoneName());
System.out.println(
"__________________________isNew() called for " + this.getClass().getSimpleName() + "result= " + result);
return result;
}
public static void setZoneNamesList(Set<String> zoneNamesListNew) {
zoneNamesList = zoneNamesListNew;
}
}
#Getter
#Setter
#Embeddable
public class ZoneDTO_Id implements GenericPJM_Id {
String zoneName;
}
#Entity
#Getter
#Setter
public class ZonePointDTO implements GenericPJM<Long> {
#JsonIgnore #Id #GeneratedValue private Long id;
private double xValue;
private double yValue;
private Integer polygonNumber;
#ManyToOne private ZoneDTO zoneDTO;
}
The JSON format I am sending:
{
"type":"ZoneDTO",
"id": {"zoneName":"SAMPLE"},
"noOfPolygons": 1,
"zonePointsList": [
{
"type":"ZonePointDTO",
"xValue": 10,
"yValue": 39.5,
"polygonNumber": 1
},
{
"type":"ZonePointDTO",
"xValue": 10,
"yValue": 39,
"polygonNumber": 1
}
]
}
I want to cascade persist the parent object(ZoneDTO), all at once and hopefully minimal DB calls.
Currently, data is getting persisted, both parent and child. But the child mapping column is saving nulls.
Any comments or workarounds or other methods will be helpful.
Thanks in advance.
Hello:) i really hope i can find help here!
the Problem: Im using Spring JPA, have created a basic REST Service, i added my Database, and i can find data in the databaste via entitymanager.createQuery()
BUT when i try to search for a timestamp or a datetime, it gives me this error:
15:12 SELECT b FROM StationsMessung b WHERE b.AVNR=:AVNR AND
b.TXNR=:TXNR AND b.DBTM=:DATUM
java.lang.ClassCastException: java.lang.String cannot
be cast to java.util.Date
at org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor.unwrap(JdbcTimestampTypeDescriptor.java:24)
at org.hibernate.type.descriptor.sql.TimestampTypeDescriptor$1.doBind(TimestampTypeDescriptor.java:48)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:74)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:280)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:275)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:53)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:628)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:2001)
at
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1915)
at org.hibernate.... (show balloon)
i know it says it cannot convert String to java.util.Date, but i dont know how to solve it.thanks for every helper!
/////////////////////////////////////////////////////////ENTITY CLASS
#Entity
#IdClass(StationsMessung.class)
#Table(name = "****", schema = "***")
public class StationsMessung implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "AVNR")
private int AVNR; ////
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "TXNR")
private int TXNR;
#GeneratedValue(strategy = GenerationType.AUTO)
#Temporal(TemporalType.TIMESTAMP)
#Type(type = "date")
#Column(name = "DBTM")
private Timestamp DBTM;
public StationsMessung(int AVNR, int TXNR, Timestamp DBTM) {
this.AVNR = AVNR;
this.TXNR = TXNR;
this.DBTM = DBTM;
}
public StationsMessung() {
}
public int getAvnr() {
return AVNR;
}
public void setAvnr(int AVNR) {
this.AVNR = AVNR;
}
public int getTxnr() {
return TXNR;
}
public void setTxnr(int TXNR) {
this.TXNR = TXNR;
}
public Timestamp getDBTM() {
return DBTM;
}
public void setDBTM(Timestamp DBTM) {
this.DBTM = DBTM;
}
///////////////////////////////////////////////////////////SERVICE CLASS
#Service
public class StationService {
#PersistenceContext
EntityManager entityManager;
public List<Station> getAllStationMessungen(int AVNR, int TXNR, Timestamp DATUM) {
return entityManager.createQuery("SELECT b FROM StationsMessung b WHERE b.AVNR=:AVNR AND b.TXNR=:TXNR AND b.DBTM=:DATUM")
.setParameter("TXNR",TXNR )
.setParameter("AVNR",AVNR )
.setParameter("DATUM", DATUM)
.getResultList();
}
////////////////////////////////////////////////////////////CONTROLER CLASS
#RestController
#RequestMapping("/station")
public class StationController {
#Autowired //This annotation allows Spring to resolve and inject
collaborating beans into your bean
StationService stationService; //service
#RequestMapping(value = "/allmessungen/{AVNR}/{TXNR}/{DATUM}", method =
RequestMethod.GET)
public List<Station> getAllStationMessungen(#PathVariable int AVNR, int
TXNR, Timestamp DATUM) {
return stationService.getAllStationMessungen( AVNR, TXNR, DATUM);
}
now when i search for data without the timestamp,it shows me data,it works.
when i use a timestamp or date it shows me the error above.
THE INPUT OF ME IS:
PARAM.1 AVNR: 716
PARAM.2 TXNR: 1339
PARAM.3 DBTM: 2014-01-04 05:30:00
(its this format yyyy-mm-dd-hh24:mi:ss)
thanks for every help:)
I have 2 Entities: Employee and Specialty.
Every Employee can have some Specialties.
POJOs are generated.
#Entity(indices = {#Index(value = {"f_name", "l_name", "birthday",
"avatarLink"}, unique = false)}, inheritSuperIndices = true)
public class Employee implements Serializable {
#PrimaryKey(autoGenerate = true)
private int employeeId;
private String f_name;
private String l_name;
private String birthday;
#Ignore
private int age;
private String avatarLink;
#Embedded
private List<Specialty> specialty;
private final static long serialVersionUID = -8824149947485321362L;
#Ignore
public Employee() {
}
public Employee(int employeeId, String f_name, String l_name, String
birthday, String avatarLink, List<Specialty> specialty) {
this.employeeId = employeeId;
this.f_name = f_name;
this.l_name = l_name;
this.birthday = birthday;
this.avatarLink = avatarLink;
this.specialty = specialty;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
And some more setters\getters...
And Specialty
#Entity
public class Specialty implements Serializable {
#PrimaryKey
private int specId;
private String specName;
private final static long serialVersionUID = 4288061416169200241L;
public Specialty(int specId, String specName) {
this.specId = specId;
this.specName = specName;
}
#Ignore
public Specialty() {
}
public int getSpecId() {
return specId;
}
And some more setters\getters...
I have this error:
error: Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
I check so many questions and read docs, but it not helps me. Thank you
you should add #Ignore to serialVersionUID fields.
In view of Room, it's just another column.
#Ignore
private final static long serialVersionUID = 4288061416169200241L;
In my class Organisation I have an attribute which is a Map and I want to save it in the database.
I've tried a lot with #ManyToMany-Annotation and also with #ElementCollection but it doesn't work.
Here is my code:
#Entity
public class Organisation extends Model {
#Id
private Long id;
private Map<ClassA, ClassB> map;
public Organisation(ClassA firstEntry){
this.map = new HashMap<ClassA,ClassB>();
ClassB value = new ClassB();
value.save();
map.put(firstEntry, value);
}
public Map<ClassA,ClassB> getMap(){
return map;
}
public void setMap(Map<ClassA,ClassB> map){
this.map = map;
}
}
An the two other classes:
#Entity
public class ClassA extends Model{
#Id
private Long id;
...
public ClassA(){
...
}
public Long getId(){
return id;
}
...
}
#Entity
public class ClassB extends Model{
#Id
private Long id;
...
public ClassB(){
...
}
public Long getId(){
return id;
}
...
}
I can create all the objects and they all are in the database. But if I try to get them out, the map is allway null. (and I can't find a table which connects Organisation, ClassA an ClassB