Update Query using composite PrimaryKey - java

I'm trying to update a column in a table with a composite primaryKey using Hibernate.
I have written sql preparedStatement for the same.
#Entity
#Table(name = "STUDENT")
Class Student{
#EmbeddedId
private StudentKey studKey;
#Column(name = "STUD_NAM")
private String name;
.....
}
#Embeddable
public class StudentKey implements Serializable {
#Column(name = "STUD_ID")
private int studId;
#Column(name = "R_RUL_BEG_DT")
private java.sql.Date beginDate;
....
}
Query :
update Student set priority=(priority+1) where studKey.studId = ? and priority between ? and ?
I'm Getting the below exception,
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'studKey.studId' in 'where clause'.
Any Suggestions please? I cant use entity objects for update operation (session.saveOrupdate()),
since i will be constructing this query dynamically based on some conditions.

Related

The column name is not valid in springboot

I wrote native query but I'm getting an error:
The column name covidSymptomId is not valid.
What's wrong?
There are table in mssql
Error picture
CovidSymptom.java
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name="CovidSymptom")
public class CovidSymptom {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "covidSymptomId")
private int id;
#ManyToOne
#JoinColumn(name = "covidId")
private Covid covidSymptom;
#Column(name = "symptom")
private String symptom;
}
CovidSymptomDao.java
#Query(nativeQuery = true,value = "Select symptom From CovidSymptom GROUP BY symptom order by count(covidSymptomId) desc")
List<CovidSymptom> getMost3SymptomOffCovid();
You need to include all columns that are mapped in your query. So:
Select covidSymptomId, symptom....
I'm not sure why you're getting a column name problem, since your select query returns a list of "symptom"(String), whilst your method provides a list of "CovidSymptom" (Object).

Hibernate Unknow Column at save() after rename column

I had a column useless_id in table foo. This column is foreign key into other table.
I have mapped it like this
#Entity
#Table(name = "foo")
public class Foo{
#Column(name = "useless_id")
private Integer uselessId;
//...
}
Everything worked perfect. But I decided to change the name of column useless_id into useful_id.
After that appear problems. When I try to save an Foo object: session.save(new Foo(...)) I get Unknown column F.useless_id in 'where clause'.
The query is printed in console insert into foo (..., useful_id, ...) value (...)
In list of columns I don't see useless_id.
Why I get Unknow column useless_id in 'where clause' ? Why use where when insert?
It is was changed everywhere. Even in Foo object
I get this error only when try to save.
UPDATE(Foo class is Order Class and useful_id is customer_id):
#Entity
#Table(name = "orders")
public class Order{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "status")
private Integer status;
#Column(name = "customer_id")
private Integer customerId;
#Column(name = "shipping_address")
private String shippingAddress;
//setters getters
}
#Entity
#Table(name = "customers")
public class Customer{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
//setters getters
}
This is how I try to insert new object
//...
session.beginTransaction();
Order order = new Order();
//set random values. customer_id get valid value, it exists in customers
session.save(order);
session.getTransaction().commit();
session.close();
For DESCRIBE orders; command I get:
Field----------------Type-----------Null---Key---Default---Extra
id-------------------int(11)--------NO-----PRI---NULL------auto_increment
status---------------int(50)--------NO-----------NULL------
customer_id----------int(50)--------NO-----MUL---NULL------
shipping_address-----varchar(191)---NO-----------NULL------
I found the problem.
It raised from MySQL. I found it by tried to insert with SQL command, direct to MySQL. Same error.
So I was looking very carefully in db and I found the problem is from triggers. In one of triggers still use old name of column.
Now make sense: Unknow column useless_id in 'where clause'. That where clause was in trigger which try to find useless_id, but it no longer exists.
CONCLUSION: After change name of column, check triggers.
In your java class you changes column name from useless_id to userful_id, but same think you didnt changes in your DB structure due to which you see this error.

Can i get data from multiple tables without jointables or foreign keys at them

I'm trying to get a single data from two tables of database. These tables doesn't have foreign keys and no jointables too. I'm using spring-data to retrieve required data for first data set.
I have two data sets that have a common String value, and want to retrieve data from both tables not using jointables or foreign keys, retrieving data from the first data set.
I'm using simple DataRepository interface
import org.springframework.data.jpa.repository.JpaRepository;
public interface DataRepository extends JpaRepository<FirstData, Long> {
DataService getById(Long id);
}
FirstData entity:
#Data
#Entity
#Table(schema = "someschema", name = "firstdata")
public class FirstData {
#Id
#Column(name = "id")
private Long uuid;
#Column(name = "name")
private String name;
#Column(name = "type")
private String type;
}
SecondData entity:
#Data
#Entity
#Table(schema = "someschema", name = "seconddata")
public class SecondData {
#Id
#Column(name = "id")
private Long uuid;
#Column(name = "type")
private String type;
#Column(name = "value")
private String value;
}
and DataService
#Service
public class DataService {
private DataRepository dataRepository;
public DataService(DataRepository dataRepository){
this.dataRepository = dataRepository;
}
public void getBothFirstAndSecondData() {
List<FirstData> firstDataSet = dataRepository.findAll();
}
}
I need to get data from both tables, but don't want to modify table structure, make jointable or add foreign keys. Also, i don't want to add another repository write code arount second data set. I need just to have a "value" from second data set at first data set result. What is the simpliest approach for solving such data retrieveing?
sql query the above problem can be:
select value from seconddata where id IN (select id from firstdata)

org.springframework.orm.jpa.JpaSystemException: ERROR: missing FROM-clause entry for table "attributeid"

Query to fetch data:
JPA not able to read attributeId table.
-- select query to fetch data
select r,a from data r ,
Attributes a
where a.attributeId.type != 'test'
and r.typeid = a.attributeId.typeid
and r.deviceid=:deviceid order by r.typeid;
-- table1
#Entity
#Table(name = "data")
public class data {
#Id
#Column(name = "typeid")
private Integer typeid;
--- table 2
#Entity
#Table(name = "attributes")
public class Attributes implements Serializable {
#EmbeddedId
private Attributeid attributeId;
#Column
private String value;
-- Class with composite keys
#Embeddable
public class Attributeid implements Serializable {
#Column
private Integer typeid;
#Column
private String type;
#Column
private String attributename;
Your query is wrong. It's JPQL not SQL so you have to join with on clause.
It should be
select r, a from data r join Attributes a on r.typeid = a.attributeId.typeid
where a.attributeId.type != 'test'
and r.deviceid=:deviceid order by r.typeid;
Is the relationship to Attributes oneToOne or onToMany?
The question is why you don't map the relationship but the only the attributes?

How hibernate retrieve data from existing database view?

I'm new to hibernate. My problem is that I have an Oracle database. I have a view in the database. Now I want to use hibernate to retrieve data in that view. Is there any possible solutions?
Below Snippet can solve your problem, which has been extracted from the tutorial: Mapping Hibernate Entities to Views
Database Query
CREATE OR REPLACE VIEW cameron AS
SELECT last_name AS surname
FROM author
WHERE first_name = 'Cameron';
view entity
#Entity
#NamedNativeQuery(name = "findUniqueCameronsInOrder", query = "select * from cameron order by surname", resultClass = Cameron.class)
public class Cameron implements java.io.Serializable {
private static final long serialVersionUID = 8765016103450361311L;
private String surname;
#Id
#Column(name = "SURNAME", nullable = false, length = 50)
public String getSurname() {
return surname;
}
public void setSurname(final String surname) {
this.surname = surname;
}
}
Hibernate mapping file.
<mapping class="examples.hibernate.spring.query.domain.Cameron" />
finally some test !...
#Test
public void findTheCameronsInTheView() throws Exception {
final List<Cameron> camerons = findUniqueCameronsInOrder();
assertEquals(2, camerons.size());
final Cameron judd = camerons.get(0);
final Cameron mcKenzie = camerons.get(1);
assertEquals("Judd", judd.getSurname());
assertEquals("McKenzie", mcKenzie.getSurname());
}
A view is from accessing data nothing different from table, a problem arises when you want to add,update or delete from view.
Please read http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/querysql.html
It' very similar to mapping ordinary database table.
Create an Entity and use your view name as Table name.
#Entity
#Table(name = "rc_latest_offer_details_view")
public class OfferLatestDetailsViewEntity {
#Id
#Column(name = "FK_OFFER_ID")
private int offerId;
#Column(name = "MAX_CHANGED_DTM")
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime changedDateTime;
private BigDecimal price;
...
}
Then query for entities same way as you do for normal table.
Working in Hibernate 4, Spring 4.
we can achieve this by using # Immutable annotation in entity class to map database view with Hibernate
For example : I have created one database view user_data which have 2 columns (id and name) and mapped user_data view in the same way as database tables.
#Entity
#Table(name = "user_data")
#Immutable
public class UserView {
#Id
#Column(name = "ID")
private int ID ;
#Column(name = "NAME")
private String name ;
}

Categories

Resources