Cannot Convert String to Timespamp inside REST - database

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:)

Related

React.js - get enum values from class in Spring Boot

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?

How to fetch data from database using hibernate ManyToMany

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

Hibernate filters are not working for APIs returning single result

I have added Hibernate filters on my entities . These filters are applied on queries which fetch Collection of entity but not applied on queries which fetch single entity. Below is my code.
AOrganization.java
#MappedSuperclass
#FilterDef(name = "OrgFilter", parameters = { #ParamDef(name = "allowedOrgIdList", type = "long") })
#Filter(name = "OrgFilter", condition = "org_id in (:allowedOrgIdList)")
public class AOrganization implements Serializable {
#ManyToOne()
#JoinColumn(name = "org_id", nullable = true)
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
Site.java
#Data
#Entity
#Table(name = "site")
public class Site extends AOrganization{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "site_name")
private String siteName;
#Override
public String toString() {
return "Site [id=" + id + ", siteName=" + siteName + "]";
}
}
SiteService.java
public interface SiteService {
public List<Site> getAllSites();
public List<Site> getSiteBySiteName(String siteName);
public Site updateSiteName(Long id, String siteName);
}
SiteRepository.java
#Repository
public interface SiteRepository extends AOrganizationRepository<Site, Long> {
public List<Site> findBySiteName(String siteName);
public List<Site> findByOrganization_Id(Long orgId);
}
AOrganizationRepository.java
#NoRepositoryBean
public interface AOrganizationRepository<T, ID extends java.io.Serializable> extends CrudRepository<T, ID> {
}
SiteServiceImpl.java
#Service
public class SiteServiceImpl implements SiteService {
#Autowired
private EntityManager entityManager;
#Autowired
private SiteRepository siteRepository;
#Override
public List<Site> getAllSites() {
Iterable<Site> sites = siteRepository.findAll();
List<Site> allSites = new ArrayList<>();
sites.forEach(allSites::add);
return allSites;
}
#Override
public List<Site> getSiteBySiteName(String siteName) {
List<Site> allSites = siteRepository.findBySiteName(siteName);
return allSites;
}
#Override
public Site updateSiteName(Long id,String siteName) {
Site site = siteRepository.findById(id).get();
if(site == null)
return null;
site.setSiteName(siteName);
siteRepository.save(site);
return site;
}
}
AOrganizationAspect.java
#Aspect
#Component
#Slf4j
public class AOrganizationAspect {
#PersistenceContext
private EntityManager entityManager;
#Pointcut("execution(public * com.harshal.springboot.springfilter.repository.AOrganizationRepository+.*(..))")
protected void aOrganizationRepositoryRepositoryMethod() {
log.info("aOrganizationRepositoryRepositoryMethod");
}
#Around(value = "aOrganizationRepositoryRepositoryMethod()")
public Object enableOwnerFilter(ProceedingJoinPoint joinPoint) throws Throwable {
// Variable holding the session
Session session = null;
try {
// Get the Session from the entityManager in current persistence context
session = entityManager.unwrap(Session.class);
// Enable the filter
Filter filter = session.enableFilter("OrgFilter");
// Set the parameter from the session
List<Long> orgList = getAllowedOrgIdList();
filter.setParameterList("allowedOrgIdList", orgList);
} catch (Exception ex) {
// Log the error
log.error("Error enabling OrgFilter : Reason -" + ex.getMessage());
}
// Proceed with the joint point
Object obj = joinPoint.proceed();
// If session was available
if (session != null) {
// Disable the filter
session.disableFilter("OrgFilter");
}
// Return
return obj;
}
private List<Long> getAllowedOrgIdList() {
return Arrays.asList(2l);
}
}
So , hibernate filters are applied if method getSiteBySiteName is called and filters are not applied if findById method is called.
Below are queries :
For getSiteBySiteName :
select site0_.id as id1_2_, site0_.org_id as org_id3_2_,
site0_.site_name as site_nam2_2_ from site site0_ where site0_.org_id
in (?) and site0_.site_name=?
Please help . Thanks in advance.
For findById
select site0_.id as id1_2_0_, site0_.org_id as org_id3_2_0_,
site0_.site_name as site_nam2_2_0_, organizati1_.id as id1_1_1_,
organizati1_.address as address2_1_1_, organizati1_.org_name as
org_name3_1_1_ from site site0_ left outer join organization
organizati1_ on site0_.org_id=organizati1_.id where site0_.id=?
findById is using the EntityManager.find method and do not create a query.
Plus Hibernate Filters only work on queries.
You should write a query instead of using findById

SpringBoot : RestAPI Returning JSON Array But I want value with label to set in AngularJS

Requirement:
Trying to populate all UNIQUE record in Angular Drop Down List
I am using predefined Table have already data.
REST API URL => http://localhost:8080/getAllCategory
Facing Problem:
API is giving the reponse in JSON Array like [xxx,yyyy,zzzz]. So I am thinking if I can convert JSON Array with some label value which can solve my problem.
Either any other way to get over with this issue.
Note :
If I am not using the native query and using the below code then I am getting all the table value in JSON with label and populating all the record in drop down but I want only UNIQUE
#Repository
public interface CategoryRepository extends JpaRepository<ccCategory,Integer>
{}
My Implementation :
Model :
#Table(name = "cccategory")
public class ccCategory
{
#Id
#Column(name = "[catid]")
public Integer catID;
#Column(name = "[categoryname]")
public String categoryName;
#Column(name = "[active]")
public int active;
public ccCategory() {
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
}
Repository:
#Repository
public interface CategoryRepository extends JpaRepository<ccCategory,Integer>
{
public static final String FIND_CATEGORYNAME = "SELECT DISTINCT catID,categoryName from ccCategory";
#Query(value = FIND_CATEGORYNAME, nativeQuery = true)
List<ccCategory> getByactive(int active);
}
Controller :
#GetMapping("/getAllCategory")
public List<Object> getAllCategory() {
// public List<ccCategory> getAllCategory() {
System.out.println("***** Call : API getAllCategory() ******");
List<Object> cCategory = categoryRepository.getCategoryName();
return categoryData;
}

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near 'auto_increment'

When I try to build a table in Azure, it says "com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near 'auto_increment'."
However, when I build in my local database, it's fine.
Can anyone help me with this? Thank you so much.
And I don't know where to fix the auto_increment rule, I didn't write it.
This is local driver I used before
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
This is my MS JDBC driver
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
This is my table class
#Entity
#Table(name = "notes")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class Note implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank
private String title;
#NotBlank
private String content;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date createdAt;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updatedAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
After I used this driver, it works. Thank you Greg!

Resources