executing stored procedure from Spring-Hibernate using Annotations - java

I'm trying to execute a simple stored procedure with Spring/Hibernate using Annotations.
Here are my code snippets:
DAO class:
public class UserDAO extends HibernateDaoSupport {
public List selectUsers(final String eid){
return (List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws
HibernateException, SQLException
{
Query q = session.getNamedQuery("SP_APPL_USER");
System.out.println(q);
q.setString("eid", eid);
return q.list();
}
});
}
}
my entity class:
#Entity
#Table(name = "APPL_USER")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorFormula(value = "SUBSCRIBER_IND")
#DiscriminatorValue("N")
#NamedQuery(name = "req.all", query = "select n from Requestor n")
#org.hibernate.annotations.NamedNativeQuery(name = "SP_APPL_USER",
query = "call SP_APPL_USER(?, :eid)", callable = true, readOnly = true, resultClass = Requestor.class)
public class Requestor {
#Id
#Column(name = "EMPL_ID")
public String getEmpid() {
return empid;
}
public void setEmpid(String empid) {
this.empid = empid;
}
#Column(name = "EMPL_FRST_NM")
public String getFirstname() {
return firstname;
}
...
}
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
APFUser user = (APFUser)ctx.getBean("apfUser");
List selectUsers = user.getUserDAO().selectUsers("EMP456");
System.out.println(selectUsers);
}
}
and the stored procedure:
create or replace PROCEDURE SP_APPL_USER (p_cursor out sys_refcursor, eid in varchar2)
as
empId varchar2(8);
fname varchar2(50);
lname varchar2(50);
begin
empId := null;
fname := null;
lname := null;
open p_cursor for
select l.EMPL_ID, l.EMPL_FRST_NM, l.EMPL_LST_NM
into empId, fname, lname
from APPL_USER l
where l.EMPL_ID = eid;
end;
If i enter invalid EID, its returning empty list which is OK.
But when record is there, following exception is thrown:
Exception in thread "main" org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not execute query; bad SQL grammar [call SP_APPL_USER(?, ?)]; nested exception is java.sql.SQLException: Invalid column name
Do I need to modify the entity(Requestor.class) ?
How will the REFCURSOR be converted to the List?
The stored procedure is expected to return more than one record.

That's because of the bug in the hibernate.
I've modified the stored procedure to fetch all the columns and it worked well.

Related

How to fix missing descriptor for class POJO after update server? [duplicate]

I'm using EclipseLink to run some Native SQL. I need to return the data into a POJO. I followed the instructions at EclipseLink Docs, but I receive the error Missing descriptor for [Class]
The query columns have been named to match the member variables of the POJO. Do I need to do some additional mapping?
POJO:
public class AnnouncementRecipientsFlattenedDTO {
private BigDecimal announcementId;
private String recipientAddress;
private String type;
public AnnouncementRecipientsFlattenedDTO() {
super();
}
public AnnouncementRecipientsFlattenedDTO(BigDecimal announcementId, String recipientAddress, String type) {
super();
this.announcementId = announcementId;
this.recipientAddress = recipientAddress;
this.type = type;
}
... Getters/Setters
Entity Manager call:
public List<AnnouncementRecipientsFlattenedDTO> getNormalizedRecipientsForAnnouncement(int announcementId) {
Query query = em.createNamedQuery(AnnouncementDeliveryLog.FIND_NORMALIZED_RECIPIENTS_FOR_ANNOUNCEMENT, AnnouncementRecipientsFlattenedDTO.class);
query.setParameter(1, announcementId);
return query.getResultList();
}
I found out you can put the results of a Native Query execution into a List of Arrays that hold Objects. Then one can iterate over the list and Array elements and build the desired Entity objects.
List<Object[]> rawResultList;
Query query =
em.createNamedQuery(AnnouncementDeliveryLog.FIND_NORMALIZED_RECIPIENTS_FOR_ANNOUNCEMENT);
rawResultList = query.getResultList();
for (Object[] resultElement : rawResultList) {
AnnouncementDeliveryLog adl = new AnnouncementDeliveryLog(getAnnouncementById(announcementId), (String)resultElement[1], (String)resultElement[2], "TO_SEND");
persistAnnouncementDeliveryLog(adl);
}
You can only use native SQL queries with a class if the class is mapped. You need to define the AnnouncementRecipientsFlattenedDTO class as an #Entity.
Otherwise just create the native query with only the SQL and get an array of the data back and construct your DTO yourself using the data.
Old question but may be following solution will help someone else.
Suppose you want to return a list of columns, data type and data length for a given table in Oracle. I have written below a native sample query for this:
private static final String TABLE_COLUMNS = "select utc.COLUMN_NAME, utc.DATA_TYPE, utc.DATA_LENGTH "
+ "from user_tab_columns utc "
+ "where utc.table_name = ? "
+ "order by utc.column_name asc";
Now the requirement is to construct a list of POJO from the result of above query.
Define TableColumn entity class as below:
#Entity
public class TableColumn implements Serializable {
#Id
#Column(name = "COLUMN_NAME")
private String columnName;
#Column(name = "DATA_TYPE")
private String dataType;
#Column(name = "DATA_LENGTH")
private int dataLength;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public int getDataLength() {
return dataLength;
}
public void setDataLength(int dataLength) {
this.dataLength = dataLength;
}
public TableColumn(String columnName, String dataType, int dataLength) {
this.columnName = columnName;
this.dataType = dataType;
this.dataLength = dataLength;
}
public TableColumn(String columnName) {
this.columnName = columnName;
}
public TableColumn() {
}
#Override
public int hashCode() {
int hash = 0;
hash += (columnName != null ? columnName.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof TableColumn)) {
return false;
}
TableColumn other = (TableColumn) object;
if ((this.columnName == null && other.columnName != null) || (this.columnName != null && !this.columnName.equals(other.columnName))) {
return false;
}
return true;
}
#Override
public String toString() {
return getColumnName();
}
}
Now we are ready to construct a list of POJO. Use the sample code below to construct get your result as List of POJOs.
public List<TableColumn> findTableColumns(String table) {
List<TableColumn> listTables = new ArrayList<>();
EntityManager em = emf.createEntityManager();
Query q = em.createNativeQuery(TABLE_COLUMNS, TableColumn.class).setParameter(1, table);
listTables = q.getResultList();
em.close();
return listTables;
}
Also, don't forget to add in your POJO class in persistence.xml! It can be easy to overlook if you are used to your IDE managing that file for you.
Had the same kind of problem where I wanted to return a List of POJOs, and really just POJOs (call it DTO if you want) and not #Entity annotated Objects.
class PojoExample {
String name;
#Enumerated(EnumType.STRING)
SomeEnum type;
public PojoExample(String name, SomeEnum type) {
this.name = name;
this.type = type;
}
}
With the following Query:
String query = "SELECT b.name, a.newtype as type FROM tablea a, tableb b where a.tableb_id = b_id";
Query query = getEntityManager().createNativeQuery(query, "PojoExample");
#SuppressWarnings("unchecked")
List<PojoExample> data = query.getResultList();
Creates the PojoExample from the database without the need for an Entity annotation on PojoExample. You can find the method call in the Oracle Docs here.
edit:
As it turns out you have to use #SqlResultSetMapping for this to work, otherwise your query.getResultList() returns a List of Object.
#SqlResultSetMapping(name = "PojoExample",
classes = #ConstructorResult(columns = {
#ColumnResult(name = "name", type = String.class),
#ColumnResult(name = "type", type = String.class)
},
targetClass = PojoExample.class)
)
Just put this anywhere under your #Entity annotation (so in this example either in tablea or tableb because PojoExample has no #Entity annotation)

How to implement Server-side processing of DataTables with JDBC so that it paginates?

I have a Spring Boot app with DataTables server-side processing and Oracle database. Actually, I started with implementing one of the tutorials. It worked. The tutorial uses JPA. I want to implement the same using JDBC. I made all the corresponding classes, the repository, the new model with same filds but without jpa. But when I tried to fetch the data, it allowed me to get only the first page without a chance to get to the second page. Below I will post the extracts of the original and added code. So, the original tutorial used these classes:
#Entity
#Table(name = "MYUSERS")
public class User {
#Id
#Column(name = "USER_ID")
private Long id;
#Column(name = "USER_NAME")
private String name;
#Column(name = "SALARY")
private String salary;
...getters and setters
}
And
#Entity
public class UserModel {
#Id
private Long id;
private String name;
private String salary;
private Integer totalRecords;
#Transient
private Integer rn;
...getters and setters
}
And I substituted these two classes with one like this:
public class NewUser {
private Long id;
private String name;
private String salary;
private Integer totalRecords;
private Integer rn;
...getters and setters
}
The table itself has only 3 fields: id, name and salary, the other 2 fields are created and filled later.
The repositiry the original Author has for the user looks like this:
public interface UserRepository extends JpaRepository<User, Long> {
#Query(value = "SELECT * FROM MYUSERS", nativeQuery = true)
List<User> findAllByUsernames(List<String> listOfUsernames);
}
My own repository looks like this:
#Repository
public class NewUserRepoImpl extends JdbcDaoSupport implements NewUserRepo {
private static final String SELECT_ALL_SQL = "SELECT USER_ID as id, USER_NAME as name, SALARY as salary FROM MYUSERS";
private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
private final JdbcTemplate jdbctemplate;
public NewUserRepoImpl(NamedParameterJdbcTemplate namedParameterJdbcTemplate, JdbcTemplate jdbctemplate, DataSource dataSource) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
this.jdbctemplate = jdbctemplate;
setDataSource(dataSource);
}
#Override
public List<NewUser> findAll(PaginationCriteria pagination) {
try {
String paginatedQuery = AppUtil.buildPaginatedQueryForOracle(SELECT_ALL_SQL, pagination);
return jdbctemplate.query(paginatedQuery, newUserRowMapper());
} catch (DataAccessException e) {
throw new EntityNotFoundException("No Entities Found");
}
}
#Bean
public RowMapper<NewUser> newUserRowMapper() {
return (rs, i) -> {
final NewUser newUser = new NewUser();
newUser.setId(rs.getLong("ID"));
newUser.setName(rs.getString("NAME"));
newUser.setSalary(rs.getString("SALARY"));
newUser.setTotalRecords(rs.getInt("TOTAL_RECORDS"));
newUser.setTotalRecords(rs.getInt("RN"));
return newUser;
};
}
}
the buildPaginatedQueryForOracle thing transforms my Query and allows it to get the totalRecords and rn. Below I will post the output of it both for the orifinal and my queries (they are the same, I checked).
So, the main part, the controller. I left the old and new pieces in it for now for debug purposes and just returning one of the results:
#RequestMapping(value="/users/paginated/orcl", method=RequestMethod.GET)
#ResponseBody
public String listUsersPaginatedForOracle(HttpServletRequest request, HttpServletResponse response, Model model) {
DataTableRequest<User> dataTableInRQ = new DataTableRequest<User>(request);
System.out.println(new Gson().toJson(dataTableInRQ));
DataTableRequest<NewUser> dataTableInRQNew = new DataTableRequest<NewUser>(request);
System.out.println(new Gson().toJson(dataTableInRQNew));
PaginationCriteria pagination = dataTableInRQ.getPaginationRequest();
System.out.println(new Gson().toJson(pagination));
PaginationCriteria paginationNew = dataTableInRQNew.getPaginationRequest();
System.out.println(new Gson().toJson(paginationNew));
String baseQuery = "SELECT USER_ID as id, USER_NAME as name, SALARY as salary FROM MYUSERS";
String paginatedQuery = AppUtil.buildPaginatedQueryForOracle(baseQuery, pagination);
String paginatedQueryNew = AppUtil.buildPaginatedQueryForOracle(baseQuery, paginationNew);
System.out.println(paginatedQuery);
System.out.println(paginatedQueryNew);
Query query = entityManager.createNativeQuery(paginatedQuery, UserModel.class);
System.out.println("Query:");
System.out.println(query);
#SuppressWarnings("unchecked")
List<UserModel> userList = query.getResultList();
System.out.println(new Gson().toJson(userList));
#SuppressWarnings("unchecked")
List<NewUser> userListNew = newUserRepo.findAll(paginationNew);
System.out.println(new Gson().toJson(userListNew));
DataTableResults<UserModel> dataTableResult = new DataTableResults<UserModel>();
DataTableResults<NewUser> dataTableResultNew = new DataTableResults<NewUser>();
dataTableResult.setDraw(dataTableInRQ.getDraw());
dataTableResultNew.setDraw(dataTableInRQNew.getDraw());
dataTableResult.setListOfDataObjects(userList);
dataTableResultNew.setListOfDataObjects(userListNew);
if (!AppUtil.isObjectEmpty(userList)) {
dataTableResult.setRecordsTotal(userList.get(0).getTotalRecords()
.toString());
if (dataTableInRQ.getPaginationRequest().isFilterByEmpty()) {
dataTableResult.setRecordsFiltered(userList.get(0).getTotalRecords()
.toString());
} else {
dataTableResult.setRecordsFiltered(Integer.toString(userList.size()));
}
}
if (!AppUtil.isObjectEmpty(userListNew)) {
dataTableResultNew.setRecordsTotal(userListNew.get(0).getTotalRecords()
.toString());
if (dataTableInRQ.getPaginationRequest().isFilterByEmpty()) {
dataTableResultNew.setRecordsFiltered(userListNew.get(0).getTotalRecords()
.toString());
} else {
dataTableResultNew.setRecordsFiltered(Integer.toString(userListNew.size()));
}
}
System.out.println(new Gson().toJson(dataTableResult));
System.out.println(new Gson().toJson(dataTableResultNew));
return new Gson().toJson(dataTableResult);
}
So, I log out everything possible in the console. Here is the output:
{"uniqueId":"1579786571491","draw":"1","start":0,"length":5,"search":"","regex":false,"columns":[{"index":0,"data":"id","name":"ID","searchable":true,"orderable":true,"search":"","regex":false,"sortDir":"ASC"},{"index":1,"data":"name","name":"Name","searchable":true,"orderable":true,"search":"","regex":false},{"index":2,"data":"salary","name":"Salary","searchable":true,"orderable":true,"search":"","regex":false}],"order":{"index":0,"data":"id","name":"ID","searchable":true,"orderable":true,"search":"","regex":false,"sortDir":"ASC"},"isGlobalSearch":false,"maxParamsToCheck":3}
{"uniqueId":"1579786571491","draw":"1","start":0,"length":5,"search":"","regex":false,"columns":[{"index":0,"data":"id","name":"ID","searchable":true,"orderable":true,"search":"","regex":false,"sortDir":"ASC"},{"index":1,"data":"name","name":"Name","searchable":true,"orderable":true,"search":"","regex":false},{"index":2,"data":"salary","name":"Salary","searchable":true,"orderable":true,"search":"","regex":false}],"order":{"index":0,"data":"id","name":"ID","searchable":true,"orderable":true,"search":"","regex":false,"sortDir":"ASC"},"isGlobalSearch":false,"maxParamsToCheck":3}
{"pageNumber":0,"pageSize":5,"sortBy":{"mapOfSorts":{"id":"ASC"}},"filterBy":{"mapOfFilters":{},"globalSearch":false}}
{"pageNumber":0,"pageSize":5,"sortBy":{"mapOfSorts":{"id":"ASC"}},"filterBy":{"mapOfFilters":{},"globalSearch":false}}
SELECT * FROM (SELECT FILTERED_ORDERED_RESULTS.*, COUNT(1) OVER() total_records, ROWNUM AS RN FROM (SELECT BASEINFO.* FROM ( SELECT USER_ID as id, USER_NAME as name, SALARY as salary FROM MYUSERS ) BASEINFO ) FILTERED_ORDERED_RESULTS ORDER BY id ASC ) WHERE RN > (0 * 5) AND RN <= (0 + 1) * 5
SELECT * FROM (SELECT FILTERED_ORDERED_RESULTS.*, COUNT(1) OVER() total_records, ROWNUM AS RN FROM (SELECT BASEINFO.* FROM ( SELECT USER_ID as id, USER_NAME as name, SALARY as salary FROM MYUSERS ) BASEINFO ) FILTERED_ORDERED_RESULTS ORDER BY id ASC ) WHERE RN > (0 * 5) AND RN <= (0 + 1) * 5
Query:
org.hibernate.query.internal.NativeQueryImpl#3ea49a4
[{"id":3,"name":"user3","salary":"300","totalRecords":18},{"id":4,"name":"user4","salary":"400","totalRecords":18},{"id":5,"name":"user5","salary":"500","totalRecords":18},{"id":6,"name":"user6","salary":"600","totalRecords":18},{"id":7,"name":"user7","salary":"700","totalRecords":18}]
[{"id":3,"name":"user3","salary":"300","totalRecords":1},{"id":4,"name":"user4","salary":"400","totalRecords":2},{"id":5,"name":"user5","salary":"500","totalRecords":3},{"id":6,"name":"user6","salary":"600","totalRecords":4},{"id":7,"name":"user7","salary":"700","totalRecords":5}]
{"draw":"1","recordsFiltered":"18","recordsTotal":"18","data":[{"id":3,"name":"user3","salary":"300","totalRecords":18},{"id":4,"name":"user4","salary":"400","totalRecords":18},{"id":5,"name":"user5","salary":"500","totalRecords":18},{"id":6,"name":"user6","salary":"600","totalRecords":18},{"id":7,"name":"user7","salary":"700","totalRecords":18}]}
{"draw":"1","recordsFiltered":"1","recordsTotal":"1","data":[{"id":3,"name":"user3","salary":"300","totalRecords":1},{"id":4,"name":"user4","salary":"400","totalRecords":2},{"id":5,"name":"user5","salary":"500","totalRecords":3},{"id":6,"name":"user6","salary":"600","totalRecords":4},{"id":7,"name":"user7","salary":"700","totalRecords":5}]}
It helped me realize that:
DataTableRequest incoming from the back is the same for both jpa
and jdbc
PaginationCriteria are also the same
paginatedQuery
having been made with the method specified above are the same.
Differences are already seen in the Lists: where the Jpa list
retrieved with native Query has totalRecords as 18 for every row,
the JDBC repo with the same query returns 1,2,3... for every
subsequent row.
It made me think that I should look at the Query made for JPA. But, as you see in the log, System.out.println wasn't able to decipher it for some reason.
Any advice on how to decipher it and more importantly how to get the right total result for each row would be greatly appreciated!!!

Is it possible to work with PostgreSQL arrays using HQL?

I've read a lot of topics dedicated to working with PostgreSQL arrays in Hibernate.
I implemented UserType interface and my queries are working perfectly fine with native sql.
private void addCountry(String country, String[] cities) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query insert = session.createNativeQuery("INSERT INTO public.\"countries\"(\n" +
"\t\"country\", \"cities\")\n" +
"\tVALUES (:Country, :Cities);");
Type arrayType = new CustomType(new StringUserType());
insert.setParameter("Country", country);
insert.setParameter("Cities", cities, arrayType);
insert.executeUpdate();
/**
CountriesEntity countriesEntity = new CountriesEntity();
countriesEntity.setCountry(country);
countriesEntity.setCities(cities);
session.save(countriesEntity);
*/
session.getTransaction().commit();
}
private List<String[]> listCities() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query getCities = session.createNativeQuery("SELECT \"cities\"\n" +
"\tFROM public.\"countries\";")
.addScalar("cities", new CustomType(new StringUserType()));
List<String[]> cities = getCities.list();
session.getTransaction().commit();
return cities;
}
Entity class:
#Entity
#Table(name = "countries", schema = "public", catalog = "Travel_Agency")
public class CountriesEntity {
private String country;
private String[] cities;
#Id
#Column(name = "country")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Column(name = "cities")
#Type(type = "com.testHibernate.core.StringUserType")
public String[] getCities() {
return cities;
}
public void setCity(String[] cities) {
this.cities = cities;
}
}
So, is it possible to do that using only HQL?
You are using createSQLQuery(String queryString) which creates a SQLQuery instance for the given SQL query string.
It is possible by using createQuery(String query) method, that will create a Query instance for the given HQL query string. For example retrieving a cities where city name is cityName:
Query getCities = session.createQuery("FROM countries WHERE cityName = :city ");
getCities.setParameter("city", "cityName");
return query.list();
Here is the documentation of The Hibernate Query Language.

Hibernate NamedQuery, set values

Good evening! I am trying to set values from my query to wrapper class TestWrapper
TestWrapper class:
package com.bionic.wrappers;
public class TestWrapper {
private String name;
private int duration;
public TestWrapper(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
}
Here is my query:
#NamedQuery(name = "getAvailableTestsNames",
query = "SELECT test.testName, test.duration FROM Result result JOIN result.test test JOIN result.user user where user.id = :userId"
and DAO class:
public List<TestWrapper> getAvailableTestsNames(long id){
Query query = em.createNamedQuery("getAvailableTestsNames");
query.setParameter("userId", id);
return (List<TestWrapper>)query.getResultList();
}
I get an exeption and i see that values won't set appropriate here:
public static Set<TestDTO> convertAvailableTestsToDTO(List<TestWrapper> tests){
Set<TestDTO> testDTOs = new HashSet<>();
for (TestWrapper test : tests){
TestDTO testDTO = new TestDTO(test.getName(), test.getDuration());
testDTOs.add(testDTO);
}
return testDTOs;
}
I get an expeption:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.bionic.wrappers.TestWrapper
Thank you!
I don't have enough context but in the getAvailableTestsNames meth. looks like you're doing a query that returns scalar results by returning "test.testName, test.duration" where you probably just want to return a List of TestWrapper so the query should just be " from XXX" , you can omit the select field1,field2 ... hibernate does that for you.
See section 11.4.1.3. Scalar results of https://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch11.html#objectstate-querying vs. 11.4.1. Executing queries
Hope this helps
Aa.

Exception: "could not set a field value by reflection setter"

When I try to read written data from hibernate database I get this error:
Exception in thread "AWT-EventQueue-0" javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not set a field value by reflection setter of familyTree.data.Data1.bio
This is class for saving my data with constructor, I pasted important part from it:
#Entity
#Table(name="DATA.PERSON")
public class Data1 {
#Id
#Column(name = "ID")
#GeneratedValue
private int id;
...
#Column(name = "BIO")
public final String bio;
...
public Data1(String names, Integer dayBirth, Integer monthBirth, Integer yearBirth, String bio, String fileID) {
this.names = names;
this.dayBirth = dayBirth;
this.monthBirth = monthBirth;
this.yearBirth = yearBirth;
this.bio = bio;
this.fileID = fileID;
}
...
public String getBiog() {
return bio;
}
So, when I try to do this:
data = new Data1(names, dayBirth, monthBirth, yearBirth, bio, fileID);
fireActionPerformed();
DatabaseUtils.spremiRezultatTesta(data);
List<?> podaci = DatabaseUtils.dohvatiRezultateTestova();
String ffff = podaci.get(0).toString();
System.out.print(ffff);
I get mentioned exception. Any help?
Database entity for that is created like this: BIO VARCHAR(80) NOT NULLand I can normally read it with SELECT FROM query in database.
Here is my DatabaseUtils class, used for saving and loading from database, if needed:
public class DatabaseUtils {
public static void spremiRezultatTesta(Data1 data) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("HibernatePersistenceUnit");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(data);
em.getTransaction().commit();
}
#SuppressWarnings("unchecked")
public static List<Data1> dohvatiRezultateTestova() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("HibernatePersistenceUnit");
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("FROM Data1");
return query.getResultList();
}
}

Categories