cant get a resultList from a Java NamedQuery - java

#Override
public com.iranatelier.sistema.dominio.Probandoblob pruebaBajarImagen() throws Exception{
com.iranatelier.sistema.dominio.Probandoblob a = new com.iranatelier.sistema.dominio.Probandoblob();
Probandoblob b = new Probandoblob();
try {
Query query = en.createNamedQuery("Probandoblob.findAll");
List lista = query.getResultList();
if (lista.size() > 0) {
for(Object c : lista){
b = (Probandoblob) c;
a.setId(b.getId());
a.setImagen(b.getImagen());
}
}
} catch (Exception e) {
throw new Exception("Error en editarEntrega:", e);
}
return a;
}
i have a sql oracle table whit a blob data type, when i try to get a result of a select from database, sendme this error.
Exception Description: Could not deserialize object from byte array.
Internal Exception: java.io.StreamCorruptedException: invalid stream header: FFD8FFE0
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[imagen-->JAAN.PROBANDOBLOB.IMAGEN]
Descriptor: RelationalDescriptor(com.iranatelier.sistema.entities.Probandoblob --> [DatabaseTable(JAAN.PROBANDOBLOB)])>
the entity are :
#Entity
#Table(name = "PROBANDOBLOB", catalog = "", schema = "JAAN")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Probandoblob.findAll", query = "SELECT p FROM Probandoblob p")
, #NamedQuery(name = "Probandoblob.findById", query = "SELECT p FROM Probandoblob p WHERE p.id = :id")})
public class Probandoblob implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#NotNull
#Column(name = "ID")
private BigDecimal id;
#Basic(optional = false)
#NotNull
#Lob
#Column(name = "IMAGEN")
private byte[] imagen;
how i can download a blob type from a data base?

Related

JPA Native Query Result Set Mapping to Entity class having child class

(column and variable name changed after posting question)i am writing join query using entityManager.createNativeQuery(somequery) in jpa custom method when i run code i get following error :
com.ibm.db2.jcc.am.SqlException: [jcc][10150][10300][4.12.56] Invalid >parameter: Unknown column name exc_seq_nbr. ERRORCODE=-4460, SQLSTATE=null
i am using IBM DB2 server and spring boot
exceptionTenderPK (object in entity class) is not being mapped correctly thats why getting invalid column can someone please tell me how to map exceptionTenderPK object class
Note: i cant use #OneToMany in this case because tables are unrelated
#Entity
#Table(name = "Table_name")
#Data
public class MainPojoclass {
#EmbeddedId
#JsonProperty(value = "mainPojoclassPK")
private MainPojoclassPK mainPojoclassPK;
#Column(name = "amt")
#JsonProperty(value = "amt")
private BigDecimal amt;
#Column(name = "tndid")
#JsonProperty(value = "tndid")
private String tndid;
#Column(name = "cde")
#JsonProperty(value = "cde")
private String cde;
#Column(name = "ind")
#JsonProperty(value = "ind")
private String ind;
#Column(name = "user")
#JsonProperty(value = "user")
private String user;
#Column(name = "updatedtime")
#JsonProperty(value = "updatedtime")
private Date updatedtime;
#Column(name = "src")
#JsonProperty(value = "src")
private String src;
#Column(name = "stat")
#JsonProperty(value = "stat")
private String stat;
}
#Transactional
public interface JoinQueryRepository extends JpaRepository<MainPojoclass, Long>, JoinQueryRepositoryCustom{
}
public interface JoinQueryRepositoryCustom {
List<MainPojoclass> getGRDetails(MainPojoclass et,Date reportDate);
}
public class JoinQueryRepositoryImpl implements JoinQueryRepositoryCustom {
#PersistenceContext
EntityManager entityManager;
#SuppressWarnings("all")
#Override
public List<MainPojoclass> getGRDetails(MainPojoclass et,Date rdate) {
String queryStr = "select et.Salss_DTE from table et"
+ " join dte etr on et.Salss_DTE = etr.Salss_DTE where et.nbr =? ";
List<MainPojoclass> datalist = null;
Query query = entityManager.
createNativeQuery(queryStr,"mapping")
.setParameter(1, 222);
datalist = query.getResultList();
return datalist;
}
}
The error says that there is no column exc_seq_nbr and you used that in your EntityResult mapping.
In your query you only return et.SLS_DTE you have to return all columns that are in the result set mapping.
Hi all since i am not getting any solutions i am going with below solution it works for me and removing #SqlResultSetMapping below code is working without sql result set mapping
Query q = em.createNativeQuery(queryStr);
List<Object[]> resultList = q.getResultList();
for (Object[] result : resultList) {
entityObj.setReason(result[0].toString);
//rest attribute will convert from result[1].toString to corresponding
// data type and set to entity object
}

java.lang.ClassCastException using JPA Queries

I'm trying to create Java EE web aplication but I have problem getting single result from database. Getting list of results isn't a problem.
public UserCredentialsDTO findByUsernameAndPassword(String username, String password) {
EntityManager em = getEntityManager();
TypedQuery<UserCredentialsDTO> q = em.createNamedQuery("UserCredentialsDTO.findByUsernameAndPassword", UserCredentialsDTO.class);
//Query q = em.createNamedQuery("UserCredentialsDTO.findByUsernameAndPassword", UserCredentialsDTO.class);
q.setParameter("un", username);
q.setParameter("pw", password);
UserCredentialsDTO r = null;
try{
r = q.getSingleResult(); //This line is a problem
//r = (UserCredentialsDTO)q.getSingleResult();
} catch(javax.persistence.NoResultException e) {
}
return r;
}
Using both Query and TypedQuery throws java.lang.ClassCastException
java.lang.ClassCastException: wipb.jee.clientdemo.model.UserCredentialsDTO cannot be cast to wipb.jee.clientdemo.model.UserCredentialsDTO
EDIT
UserCredentialsDTO:
#NamedQueries(
{#NamedQuery(name = "UserCredentialsDTO.findByUsernameAndPassword", query = "select uc from UserCredentialsDTO uc where uc.username=:un and uc.password=:pw")}
)
#Entity
#Table(name="USERCREDENTIALS", schema="APP")
public class UserCredentialsDTO implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
#OneToMany(mappedBy = "userCredentials", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private List<UserGroupDTO> userGroups = new LinkedList<>();
//getters and setters
public void add(UserGroupDTO userGroup) {
userGroup.setUserCredentials(this);
this.userGroups.add(userGroup);
}
public List<UserGroupDTO> getUserGroups() {
return userGroups;
}
}
This looks like an environment issue, where different classloaders are being used for JPA and the rest of the application.
Refer to this thread

ClassCastException with hibernate

I am trying to fetch specific fields from my entities. I need the result in my entity structure.
Following are my entities:
Country
public class CountryModel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "CmtID")
private int id;
#Column(name = "CmtName")
private String name;
#JoinColumn(name="CmtStateID")
#OneToMany(targetEntity=StateModel.class,fetch=FetchType.EAGER)
private List<StateModel> state;
}
State
public class StateModel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "SmtID")
private int id;
#Column(name = "SmtName")
private String name;
}
Following is the HQL query am executing:
Query query = session.createQuery("select c.name, s.name from CountryModel c join c.state s where c.id=2");
CountryModel stateModel = (CountryModel) query.uniqueResult();
But am getting the following error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.muziris.entity.CountryModel
Thanks for helping.
Expected result:
Country :
name : india
state :
name : kerala
name : goa
name : Pak
state :
name : karachi
Since your classes are mapped you can try:
Query query = session.createQuery("from CountryModel c where c.id=2");
CountryModel countryModel = (CountryModel) query.uniqueResult();
Let's make use of the mapping and HQL.
From there you can use a DTO to have only the data that you need
public CountryDTO transform(CountryModel cm){
String countryName = cm.getName();
List<String> stateNames = cm.getState().stream.map(StateModel::getName)
.collect(Collectors.toList());
return new CountryDTO(countryName, stateNames);
}
CountryDTO is the result that you need.
Hibernate returns List<Object[]> when you use the projections.
List<Object[]> is a list of specified projection columns.
Some links
https://stackoverflow.com/a/36883968/3405171
How to transform a flat result set using Hibernate

"Fail to convert to internal representation" while accessing changed column data with audit query

I am using envers in my project to audit data.
Now I want to access changed data with audit query.
My pojo class for table is below
#Entity
#Audited(withModifiedFlag=true)
#Table(name = "INSTRUMENT", uniqueConstraints = #UniqueConstraint(columnNames = "INSTRUMENT_NAME"))
public class Instrument implements java.io.Serializable {
private long instrumentId;
private String instrumentName;
private WorkflowState workflowState;
#Id
#Column(name = "INSTRUMENT_ID", unique = true, nullable = false, precision = 22, scale = 0)
public long getInstrumentId() {
return this.instrumentId;
}
public void setInstrumentId(long instrumentId) {
this.instrumentId = instrumentId;
}
#Column(name = "INSTRUMENT_NAME", unique = true, nullable = false, length = 50)
public String getInstrumentName() {
return this.instrumentName;
}
public void setInstrumentName(String instrumentName) {
this.instrumentName = instrumentName;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "STATUS", nullable = false)
public WorkflowState getWorkflowState() {
return this.workflowState;
}
public void setWorkflowState(WorkflowState workflowState) {
this.workflowState = workflowState;
}
}
Now I tried to access this with audit query as
AuditQuery query = reader.createQuery().forRevisionsOfEntity(Instrument.class, false, true)
.add(AuditEntity.property("status").hasChanged());
List list= query.getResultList();
So at the time of accessing getResultList() , Its throwing Exception as follows
SqlExceptionHelper: Fail to convert to internal representation
I figured it out, this is because in my db Instrument.status column is as String data Type. While here I am using Join.
So please tell me how to write query to resolve this problem
PROBLEM is How to write Audit Query if my table has foreign key (class property have join dependency).
Join table WorkflowState discription is as follows
public class WorkflowState implements java.io.Serializable {
private BigDecimal stateId;
private Workflow workflow;
private String stateName;
//getters and setters
And it has a join column too i.e "workflow" .
Use workflowState rather than status. The API is based on you specifying the property name and not the column name.

Hibernate Error SQLGrammarException (MySQL)

I try to get back a list of elements in an instance Criteria. In the execution I obtain this exception. What is the problem ?
The name of my database is "TransPlusBD".
The name of my table is a "gerant".
But the error indicates me that he(it) does not find the table "TransPlusDB.gerant_gerant", yet this table does not exist.
Normally we have to have his "TransPlusDB.gerant".
Code of the configuration
properties = new Properties();
properties.put("hibernate.dialect","org.hibernate.dialect.MySQLInnoDBDialect");
properties.put("hibernate.connection.driver_class","com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url","jdbc:mysql://(cloud amazone aws).amazonaws.com:3306/TransPlusDB");
properties.put("hibernate.connection.username","xxx");
properties.put("hibernate.connection.password","xxxxxxxxxxxx");
properties.put("hibernate.connection.pool_size","4");
configuration = new Configuration();
configuration.setProperties(properties);
configuration.addAnnotatedClass(Administrator.class);
configuration.addAnnotatedClass(AutoGare.class);
configuration.addAnnotatedClass(Car.class);
configuration.addAnnotatedClass(City.class);
configuration.addAnnotatedClass(Company.class);
configuration.addAnnotatedClass(transplus.models.Configuration.class);
configuration.addAnnotatedClass(DateDeparture.class);
configuration.addAnnotatedClass(Departure.class);
configuration.addAnnotatedClass(HoursDeparture.class);
configuration.addAnnotatedClass(Luggage.class);
configuration.addAnnotatedClass(Manager.class);
configuration.addAnnotatedClass(Passenger.class);
configuration.addAnnotatedClass(PlanningVoyage.class);
configuration.addAnnotatedClass(Route.class);
configuration.addAnnotatedClass(Stopover.class);
configuration.addAnnotatedClass(SysAdmin.class);
configuration.addAnnotatedClass(Ticket.class);
configuration.addAnnotatedClass(TypeCar.class);
configuration.addAnnotatedClass(ModificationLuggage.class);
configuration.addAnnotatedClass(ModificationTicket.class);
configuration.addAnnotatedClass(PassageRoute.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
Code of my class
#Entity
#Table(name = "gerant")
public class Manager implements Serializable // Table Gerant
{
#Id
#GeneratedValue
#Column(name = "code_gerant")
private long code_manager;
#Column(name = "matricule_gérant",unique = true)
private String matricule_manager;
#Column(name = "nom_gerant")
private String lastName_manager;
#Column(name = "prenom_gerant")
private String firstName_manager;
#Column(name = "password_gerant",nullable = false)
private String password_manager;
#Column(name = "login_gerant",unique = true,nullable = false)
private String login_manager;
#Column(name = "poste_gerant")
private String function_manager;
#Column(name = "actif_gerant")
private boolean enabled_manager;
#Enumerated(EnumType.ORDINAL)
#Column(name = "privilege_gerant")
private Privilege privilege;
#ManyToOne
#JoinColumn(name = "code_manager", foreignKey = #ForeignKey(name = "fk_gerant_manager"))
private Administrator administrator;
#ManyToOne
#JoinColumn(name = "over_gerant", foreignKey = #ForeignKey(name = "fk_over_gerant"))
private Manager overManager;
#Expose // Annotation for Gson
#OneToMany(cascade = CascadeType.ALL,orphanRemoval = false)
private List<Manager> underManagers = new ArrayList<>();
Code for the recovery of the list.
public String getAllManager()
{
if(session.isOpen())
{
Transaction transaction = null;
try
{
transaction = session.beginTransaction();
transaction.begin();
Criteria criteria = session.createCriteria(Manager.class);
List list = criteria.list();
transaction.commit();
if(list != null)
{
if(!list.isEmpty())
return serializeTab(list);
}
return null;
}
catch (Exception e)
{
if(transaction != null)
transaction.rollback();
e.printStackTrace();
}
}
return null;
}
Here is the raised exception
this = {ServiceManager#3681}
transaction = {TransactionImpl#3683}
transactionCoordinator = {JdbcResourceLocalTransactionCoordinatorImpl#3979}
transactionDriverControl = {JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl#3980}
valid = false
e = {SQLGrammarException#3954} "org.hibernate.exception.SQLGrammarException: could not extract ResultSet"
sqlException = {MySQLSyntaxErrorException#3958} "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'TransPlusDB.gerant_gerant' doesn't exist"
SQLState = "42S02"
vendorCode = 1146
next = null
detailMessage = "Table 'TransPlusDB.gerant_gerant' doesn't exist"
cause = {MySQLSyntaxErrorException#3958} "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'TransPlusDB.gerant_gerant' doesn't exist"
stackTrace = {StackTraceElement[0]#3961}
suppressedExceptions = {Collections$UnmodifiableRandomAccessList#3962} size = 0
sql = "n/a"
Help I PLEASE
The table gerant_gerant is a join table for a self association for this
#OneToMany(cascade = CascadeType.ALL,orphanRemoval = false)
private List<Manager> underManagers = new ArrayList<>();
You need to let Hibernate to create this table using the hibernate.hbm2ddl.auto property or you can create it manually with constraints ( a foreign key, a unique key).
You can specify a join table name with the #JoinTable annotation.
I added this line of code at the level of the configuration
properties.put("hbm2ddl.auto","validate");
Then this code at the level of my class
#OneToMany(cascade = CascadeType.ALL,orphanRemoval = false,mappedBy = "overManager")
private List<Manager> underManager;
Thank

Categories