I have a problem. I need to display the value from the line and transfer it to the database. I'm using a timelif, and so, I get the error "Order is not mapped", and points to line 31, in fact, to my HQL query. Structure: I enter a word in the field, the timelif transfers it to the post request of the spring, and the same transfers it to the function. It is necessary to write the request somehow correctly so that the text is entered into the database. My code:
public String createOrder (#ModelAttribute("order") Orderdao orderdao, String text){
orderdao.createOrder(text);
return "redirect:/";
}
Function:
public void createOrder(String text) {
Transaction tx = null;
try (Session session = BogPomogi.getSessionFactory().openSession()) {
session.beginTransaction();
System.out.println(text);
Query create = session.createQuery("insert into Order(text)" + "select text from text");
int result = create.executeUpdate();
session.getTransaction().commit();
session.close();
}
Help me please
i solved it with: Query query = session.createSQLQuery("INSERT INTO orders (text, status, customer) VALUES (:text, :status, :customer)");
(sql request)
Related
I try to get all data in table(SELECT * FROM) mysql database, Using real time search, But not load data to table.
I called getAll("") method with empty String, But I can't get any value from my table.
public ArrayList<Titem> getAll(String text) throws SQLException, ClassNotFoundException {
Session session = HibernateUtil.openSession();
Query query = session.createQuery("FROM titem WHERE id = :id");
query.setParameter("id",text);
List<Titem> list = query.list();
ArrayList<Titem> entityList = new ArrayList<>();
for (Titem t:list
) {
Titem titem = new Titem(
t.getId(),
t.getName(),
t.getPrice()
);
entityList.add(titem);
}
return entityList;
}
You need to conditionally remove the where statement to stop filtering on that column, empty string or null values will also be matched against the data in the table. Or you could change the query to:
FROM titem WHERE (id = :id OR :id = '')
Requirement : I have a file from which I need to add the assistant employee id corresponding to it's manager into db. So in file I am getting login id of assistant. I need to pass the login id to db in order to fetch the corresponding employee id of the assistant and add into the list which I am getting from file.
// code for getting employee from file - returns a list
private void setAssistantEmployeeId(List<E> empFile){
List<E> empFilter = empFile.stream().filter(emp -> emp.getLoginId()!=null).collect(Collectors.toList());
String sql = "SELECT ID FROM EMPLOYEE WHERE LOGIN_ID = ";
List<E> tempList = new ArrayList<>(empFilter);
for(E emp : empFilter){
tempList.addAll(jdbcTemplate.query(sql+emp.getLoginId(), (resultset,i)->{
emp.setAssistantEmployeeId(resultset.getString("ID"));
return emp;
}));
}
}
The above code is working as expected but it's taking lot of time to execute. I need some help to optimize this code. Can someone please help me in optimizing this code?
Thank you.
private void setAssistantEmployeeId(List<E> empFile) throws SQLException {
List<E> empFilter = empFile.stream().filter(emp -> emp.getLoginId()!=null).collect(Collectors.toList());
//1. query all LOGIN_ID
String sql = "SELECT ID, LOGIN_ID FROM EMPLOYEE WHERE LOGIN_ID IN (" + empFilter.stream().map(emp -> emp.getLoginId())
.collect(Collectors.joining("','")) + ")";
// create map[LOGIN_ID, ID]
ResultSet rs = runQuery(sql); // execute this query in your way
Map<String, String> id_loginId = new HashMap<>();
while (rs.next()) {
id_loginId.put(rs.getString("LOGIN_ID"), rs.getString("ID"));
}
// 3. assign ID value
empFilter.forEach(e -> {
e.setAssistantEmployeeId(id_loginId.getOrDefault(e.getLoginId(), ""));
});
}
I am insert data in db is good. The problem is after inserted data i am trying to get last inserted data primary key column. But i can't how to solve this problem.
note : i am using jpql , Thanks
public void insertData(String hcpHceId) {
EntityManager em = getEntityManager();
em.getTransaction().begin();
// Query query = em.createNativeQuery("INSERT INTO mdm_id (hcp_hce_id) VALUES(:id)" );
Query query = em.createNativeQuery("INSERT INTO mdm_id (hcp_hce_id) VALUES(?)");
query.setParameter(1, hcpHceId);
query.executeUpdate(); // Successfully inserted data
List list = query.setMaxResults(1).getResultList(); // Error line
em.getTransaction().commit();
} catch (Exception error) {
error.printStackTrace();
logger.error(error.getMessage());
} finally {
em.close();;
}
}
You are trying to retrieve the list from the same execute query. Query is an immutable object. You must create a new query with the proper select statement, so you will be able to retrieve data from database.
After the executeUpdate, create the new query using, v.g. (as you did not show your entity graph, using native sql):
Query retQuery = em.createNativeQuery("SELECT hcp_hce_id FROM mdm_id LIMIT 1");
String id = (String) retQuery.getSingleResult();
assert(id == hcpHceId);
I created one table like student and I fetched the address based on age (like age = 22). Now I want to update the address based on age "22" to all address columns of table. How can I do this?
Below is my code:
public static void main(String[] args) {
EntityManager entityManager = Persistence.createEntityManagerFactory(
"demoJPA").createEntityManager();
Query query = entityManager.createQuery("SELECT student FROM Student student WHERE student.age = 22");
System.out.println("Data is" + query.getResultList().size());
List<Simpletable> simpletable = query.getResultList();
for (Simpletable simpletable1 : simpletable){
System.out.println(simpletable1.getAddress());
}
}
I fetched data but how can I update now. Is it possible to iterate through a loop and setAddress("US")
Since you are creating a standalone application, you must open a transaction first, then you can simply change the field values in your object and when the transaction is committed, the changes get flushed to the database automatically.
EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
try {
for(SimpleTable simpleTable : simpleTables){
simplaTable.setAddress(newAddress);
}
} finally {
tx.commit();
}
} catch (Exception e) {
// handle exceptions from transaction methods
}
--Edit--
An alternative to edit all records without having to first fetch them is to do a bulk update, still within a transaction, like this:
entityManager.createQuery("UPDATE SimpleTable s " +
"SET s.address.state = ?1 " +
"WHERE s.address.country = ?2")
.setParameter(1, "FL")
.setParameter(2, "US")
.executeUpdate();
I made a class called SpecializationBean which has two private fields:
private ArrayList<SelectItem> specializationItems= new ArrayList<SelectItem>();
private String specializationName;
I have ofcourse a getter and setter for those two.
and a buildSpecializationList method which builds the specializationItems list: (I call this method in the getter):
public void buildSpecializationList(){
List<Object[]> specializations = null;
try{
Session mySession = HibernateUtil.getAdmSessionFactory().getCurrentSession();
Transaction transaction = mySession.beginTransaction();
String sql = "SELECT J_Specialization_ID, Specialization_Name_Ar FROM J_Specialization WHERE J_Department_ID = '1000001'";
Query query = mySession.createSQLQuery(sql).addScalar("id", Hibernate.LONG).addScalar("name", Hibernate.STRING);
specializations = query.list();
}
catch(Exception e){
e.printStackTrace();
}
this.specializationItems = new ArrayList<SelectItem>(90);
for(Object[] sp: specializations ){
this.specializationItems.add(new SelectItem(sp[0],(String) sp[1]));
}
}
The problem is that I get a null pointer exception which shows that the list specializations (defined in the buildSpecializationList()) is null. I have tried the query myself on the table and it returns a result. I also tried HQL query (istead):
String sqlQuery = "Select JSpecializationId, specializationNameAr FROM JSpecializationWHERE JDepartmentId = '1000001'";
Query q = mySession.createQuery(sqlQuery);
But still, I get a null pointer exception which shows that the query returns me null result. Do you have any suggestions?
For anyone who encounters this problem using Hibernate ...... creating a new class and rewriting the whole thing may actually solve the problem!!!