my action class is :-
package com.action;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.apache.struts2.convention.annotation.*;
import org.apache.struts2.rest.DefaultHttpHeaders;
import com.opensymphony.xwork2.ActionSupport;
#ParentPackage(value="default")
#Namespace("/")
#ResultPath(value="/")
public class noOfUsers extends ActionSupport {
private static final long serialVersionUID = 1L;
#Action(value="usersn",results={
#Result(name="create",type="tiles",location="users")
})
public static DefaultHttpHeaders create(){
EntityManagerFactory emf=Persistence.createEntityManagerFactory("tujpa");
EntityManager em=emf.createEntityManager();
EntityTransaction entr=em.getTransaction();
entr.begin();
Query query=em.createQuery("SELECT U.firstname from User U");
List <User> list = query.getResultList();
System.out.println("password");
Iterator iterator = list.iterator();
System.out.println("password1");
while(iterator.hasNext()){
String empFirstName = (String)iterator.next();
System.out.print("Emp Name:"+empFirstName );
System.out.println("password2");
}
entr.commit();
em.close();
return new DefaultHttpHeaders("create");
}
}
and i want to display my result list on my jsp page,
so please guide.
thanks in advance.
Okay I can see why there has not been an answer... you've taken some JPA code which prints to the terminal and then pasted that into S2 class which you've found off the Internet?
Please start with a simple "Hello World" application: http://struts.apache.org/2.2.1.1/docs/getting-started.html
When that is running, there are plenty of examples of using the iterator tag. This tag goes on the JSP, and is documented on the above listed site.
Your action code then would become something like (quick hack job):
public class UserList extends ActionSupport {
List <User> list;
public String action(){
EntityManagerFactory emf=Persistence.createEntityManagerFactory("tujpa");
EntityManager em=emf.createEntityManager();
EntityTransaction entr=em.getTransaction();
entr.begin();
Query query=em.createQuery("SELECT U.firstname from User U");
list = query.getResultList();
em.close();
return SUCCESS;
}
}
Now you should research some DI framework... S2 has good Spring integration moving the EntityManagerFactory/EntityManager handling to Spring would make the above much cleaner. Something like:
public String action(){
list = em.createQuery("SELECT U.firstname from User U").getResultList();
return SUCCESS;
}
Related
I would like to run multiple queries then show results in a page such as :
https://adminlte.io/themes/v3/index.html
I create a first controller query :
package controllers;
import models.Sysuser;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
import views.html.sitemap.index;
import javax.inject.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import play.libs.concurrent.HttpExecutionContext;
import static java.util.concurrent.CompletableFuture.supplyAsync;
import play.db.*;
import io.ebean.*;
import play.Logger;
import java.util.List;
import java.util.ArrayList;
import models.LocationExtractedData;
#Security.Authenticated(Secured.class)
public class SiteMap extends Controller {
private Database db;
private final HttpExecutionContext httpExecutionContext;
private static final Logger.ALogger logger = Logger.of(SiteMap.class);
#Inject
public SiteMap(Database db,
HttpExecutionContext httpExecutionContext) {
this.db = db;
this.httpExecutionContext = httpExecutionContext;
}
public CompletionStage<Result> index() {
return SearchSomething().thenApplyAsync((List<LocationExtractedData> infos) -> {
return ok(views.html.sitemap.index.render( Sysuser.findByUserName(request().username()), infos) );
}, httpExecutionContext.current());
}
public CompletionStage<List<LocationExtractedData>> SearchSomething() {
return CompletableFuture.supplyAsync(() -> {
return db.withConnection(
connection -> {
// Imagines this is a complexe QUERY (Later in the future...)
final String sql = "SELECT sysuser_id, role_id "
+"from sysuser_role "
+"where sysuser_id = '1' "
+"and role_id in ('1','2','3','4','5') ";
final RawSql rawSql = RawSqlBuilder.parse(sql).create();
Query<LocationExtractedData> query = Ebean.find(LocationExtractedData.class);
query.setRawSql(rawSql);
List<LocationExtractedData> list = query.findList();
return list;
});
}, httpExecutionContext.current());
}
}
Can you telling me how to run multiple and optimized queries in the same time for my page full of dashboards, charts and tables!
If i create multiple list of ebeanLists ( queries ), does this will affect the loading of my page ?
IF not, then, what should i do ?
Thank you in advance,
Typically, in an application similar to the link you have provided, you create reusable APIs following the MVC design pattern. Querying the database from the controller is very much against that pattern.
Each API should be atomic, creating a single API to run 1 query to fetch all of the data for that page is not the correct approach.
If you are looking for performance for your API you should get familiar with asynchronous programming. Running your APIs async will allow your back end to process multiple front end requests at the same time, greatly improving performance.
I was using JPA repository to get user data and store it in a list . Then is was going to iterate that list of users to get all the users. But there is an error in the forEach statement(Syntax error).
code:
package com.mohit.Services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.mohit.Repo.userrepo;
import com.mohit.beans.users;
public class loginuser {
#Autowired
userrepo Repo;
public void loguser(users user){
String pass =user.getPass();
String uname =user.getName();
List<users> userlist=Repo.findAll();
forEach( users u : userlist){
}
}
}
There is no foreach keyword in java, need to use for, so you have error in source code, please try below code for cycle, instead of your's:
for(users u : userlist){
}
I am new to Spring Jpa and Hibernate. I am trying to fetch data using a custom function from an Oracle db. I could define an entity along with its related service, implementation and repository. In addition, I created a new custom Oracle dialect by using registerFunction as you will see below.
So I have two questions:
1) In my Oracle db, the function sits under a different schema. Do I need to specify its schema? If so how? Or will hibernate find it automatically?
I will be asking my second question at the end of this post after providing my full stacktrace...
Here is my full stack trace:
MyOracle10gDialect
package blog;
import org.hibernate.dialect.Oracle10gDialect;
import org.hibernate.dialect.function.StandardSQLFunction;
public class MyOracle10gDialect extends Oracle10gDialect {
public MyOracle10gDialect() {
super();
registerFunction("my_function", new StandardSQLFunction("my_function"));
}
}
application.properties
...
spring.jpa.database-platform=blog.MyOracle10gDialect
...
Entity:
package blog.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "item", schema = "WOS_SOURCE")
public class WosItem {
#Id
#Column(nullable = false)
private String UT;
#Column(nullable = false)
private String TI;
public String getUT() {
return UT;
}
public void setUT(String UT) {
this.UT = UT;
}
public String getTI() {
return TI;
}
public void setTI(String TI) {
this.TI = TI;
}
public WosItem(String UT, String TI) {
this.UT = UT;
this.TI = TI;
}
public WosItem() { }
#Override
public String toString() {
return "WosItem{" +
"UT='" + UT + '\'' +
", TI='" + TI + '\'' +
'}';
}
}
Service:
package blog.services;
import blog.models.WosItem;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public interface WosItemService {
List<WosItem> findAll();
WosItem findById(String id);
String find_ut(Long ut_seq);
}
Implementation:
package blog.services;
import blog.models.WosItem;
import blog.repositories.WosItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class WosItemServiceJpaImpl implements WosItemService {
#Autowired
private WosItemRepository wosItemRepository;
#Override
public List<WosItem> findAll() {
return this.wosItemRepository.findAll();
}
#Override
public WosItem findById(String id) {
return this.wosItemRepository.findOne(id);
}
#Override
public String find_ut(Long ut_seq) {
return this.wosItemRepository.find_ut();
}
}
Repository:
package blog.repositories;
import blog.models.WosItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
#Repository
public interface WosItemRepository extends JpaRepository<WosItem, String> {
#Query("SELECT function('my_function', input) FROM WosItem wos");
String find_ut();
}
So in my Oracle db I can use this function as shown below:
select other_schema.my_function(aa.input) from my_schema.TABLE aa;
For ex. say aa.input is 332708100009 then it returns 000332708100009
As for my second question:
2) How can I carry out this process in jpa? I am aware that my repository is not correct at all. I get an error like "Annotations are not allowed here". I could not find a way to remedy this.
Thanks in advance.
EDIT ON THROWN EXCEPTION:
Caused by: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode
\-[METHOD_CALL] MethodNode: 'function (my_function)'
+-[METHOD_NAME] IdentNode: 'my_function' {originalText=my_function}
\-[EXPR_LIST] SqlNode: 'exprList'
\-[NAMED_PARAM] ParameterNode: '?' {name=ut_seq, expectedType=null}
Unfortunately if you want to use the JPA 2.1 feature of the custom function call in your Select statement then you will need to perform some additional actions before you can use it.
When you use it in your where statement then it works without any additional actions, but as i wanted to use it for one of my projects inside the select just as you did then you would need to:
1) Extend the hibernate dialect and register your function(s):
package com.mypkg.dialect;
import org.hibernate.dialect.Oracle10gDialect;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.type.StringType;
public class CustomOracle10gDialect extends Oracle10gDialect {
public CustomOracle10gDialect() {
super();
registerFunction("my_function"
, new StandardSQLFunction("my_function", new StringType()));
}
}
2) Edit your hibernate.dialect property of your session factory to point to that custom implementation:
<property name="hibernate.dialect" value="com.mypkg.dialect.CustomOracle10gDialect"/>
Update
If the function needs to be called from a certain schema then this would be suggested:
registerFunction("my_function"
, new StandardSQLFunction("schema.my_function", new StringType()));
Further reading -> native function calls
I'm having trouble updating records as so:
package legacy.database;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
public class Queries {
private static final Logger log = Logger.getLogger(Queries.class.getName());
private final EntityManagerFactory emf = Persistence.createEntityManagerFactory("LegacyDatabasePU");
private final EntityManager em = emf.createEntityManager();
public Queries() {
}
private List<Clients> findAll() {
Query q = em.createQuery("select c from Clients c");
List<Clients> clients = q.getResultList();
return clients;
}
public Clients findById(int id) {
Clients client = em.find(Clients.class, id);
return client;
}
public void update(Clients c2) {
Clients c1 = em.find(Clients.class, c2.getId());
java.util.Date date = new java.util.Date();
Timestamp t = new Timestamp(date.getTime());
c2.setDateUpdated(t.toString());
em.getTransaction().begin();
c2.setDateUpdated(t.toString());
c1 = c2;
log.info(c1.getNotes());
log.info(c2.getNotes());
em.getTransaction().commit();
}
}
is there a problem with assigning c1=c2? Do I have to manually go through c1 and update each record?
Do the find() within a transaction, and then call your mutating methods within the transaction. Commit will then update the object automatically. Just simple movement of the begin txn gives this. Only you know what the various updates are so no attempt is made to clean that up
try
{
em.getTransaction().begin();
Clients c1 = em.find(Clients.class, c2.getId());
Timestamp t = new Timestamp(new java.util.Date().getTime());
c2.setDateUpdated(t.toString());
c1 = c2;
log.info(c1.getNotes()); log.info(c2.getNotes());
em.getTransaction().commit();
}
finally
{
if (em.getTransaction().isActive())
{
em.getTransaction().rollback();
}
}
If the entity is not registered in the EntityManager, possibly like your c2, then it will not be updated unless you use em.persist, em.merge and so on.
And c1 = c2 is just pointing the c1 reference to the c2 reference.
From the comment below, what you want to do is to copy properties of c2 to c1, which can be done
statically calling each setter/getter with the help of an editor capable of column mode editing (IntelliJ, Eclipse, jEdit, etc)
with the use of libraries like Apache BeanUtils; this would use reflection.
In both case, you must remember to:
do a deep copy if this should be done; eg: if there is a OneToMany, you should probably duplicate the sub entities.
don't copy field that should not (like unique constraints)
I'm trying to use the Play framework (Java) to simply read some data from a few Oracle tables, probably even use a few complex queries later on. I'm following a tutorial but I'm having some issues retrieving the data.
My Model class look like this:
package models;
import java.util.ArrayList;
import java.util.List;
import play.libs.F;
import javax.persistence.*;
import com.avaje.ebean.*;
import play.db.ebean.*;
#Entity
#Table(name="TABLESPACE.CAT_BONDS")
public class Cat_Bond extends Model {
#Id
public String symbol;
public String database;
public String tickType;
public String assetClass;
public String sourcePlatform;
public String sourceExchange;
public static Finder<String, Cat_Bond> find = new Finder<String, Cat_Bond>(String.class,Cat_Bond.class);
public Cat_Bond(){}
public Cat_Bond(String symbol, String database, String tickType, String assetClass,
String sourcePlatform, String sourceExchange) {
this.symbol = symbol;
this.database = database;
this.tickType = tickType;
this.assetClass = assetClass;
this.sourcePlatform = sourcePlatform;
this.sourceExchange = sourceExchange;
}
/*
* retrieve all rows from the 'cat_bonds' table
*/
public static List<Cat_Bond> findAll(){
//return new ArrayList<Cat_Bond>(cat_bond);
return find.all();
}
/*
* Find by EAN
*/
public static Cat_Bond findByEan(String symbol){
return find.where().eq("symbol", symbol).findUnique();
}
}
My controller class:
package controllers;
import java.util.List;
import views.html.*;
import models.Cat_Bond;
import play.data.Form;
import play.mvc.*;
public class Cat_Bonds extends Controller {
private static final Form<Cat_Bond> cat_bondForm = Form.form(Cat_Bond.class);
public static Result list(){
List<Cat_Bond> cat_bond = Cat_Bond.findAll();
return ok(list.render(cat_bond));
}
And the application.conf entry looks like:
#Oracle
db.default.driver=oracle.jdbc.OracleDriver
db.default.url="jdbc:oracle:thin:#server.uk.net.intra:port/ALIAS"
db.default.user=user
db.default.password=pass
# Evolutions
# ~~~~~
# You can disable evolutions if needed
evolutionplugin=disabled
Problem is when the call to list is made in the controller then to findAll() in the model I get the error:
**[PersistenceException: Query threw SQLException:ORA-00904: "T0"."SOURCE_EXCHANGE": invalid identifier Bind values:[] Query was: select t0.symbol c0, t0.database c1, t0.tick_type c2, t0.asset_class c3, t0.source_platform c4, t0.source_exchange c5 from TABLESPACE.CAT_BONDS t0 ]**
#Column(name="xx")
Was required above each variable defined in the model class that was to be mapped to the table column.
You can use
clean
compile
~run
If it doesn't work properly, you can use #EntityConcurrencyMode(ConcurrencyMode.NONE) within your model class.