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.
Related
I have generated master tables using liquibase. I have created the corresponding models in spring boot now I want to maintain a relation ship between those models.
I have one table called Vehicle_Type, it is already pre-populated using liquibase.
#Data
#Entity
#Table(name="VEHCILE_TYPE")
public class VehicleType {
#Id
private int id;
#Column(name="DISPLAY_NAME")
private String displayName;
#Column(name="TYPE")
private String type;
#Column(name="CREATED_DATE")
private LocalDateTime createdDate;
#Column(name="UPDATED_DATE")
private LocalDateTime updateDate;
}
now what I want to achieve is, I have one child entity, I have refer the VehicleType instance inside that entity as depicted below
#Data
#Entity
#EqualsAndHashCode(callSuper = true)
#Table(name = "NON_MSIL_VEHICLE_LAYOUT")
public class NonMsilVehicleLayout extends BaseImagesAndLayout {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "NMV_SEQ")
#SequenceGenerator(sequenceName = "NON_MSIL_VEH_SEQUENCE", allocationSize = 1, name = "NMV_SEQ")
private int id;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name = "VEH_TYPE", referencedColumnName = "id")
private VehicleType vehicleType;
public interface VehType {
String getVehType();
}
}
The problem is when I tries to save entity NonMsilVehicleLayout, then it tries to first insert the data in VEHICLE_TYPE table also. which should not going to be happen.
I don't want that, I want JPA will pick the correct ID from VEHICLE_TYPE table and place it inside the corresponding table for NonMsilVehicleLayout, because the id of VEHICLE_TYPE table is act as foreign key in Non_Msil_Vehicle_Layout table.
log.info("Inside saveLayout::Start preparing entity to persist");
String resourceUri = null;
NonMsilVehicleLayout vehicleLayout = new NonMsilVehicleLayout();
VehicleType vehicleType=new VehicleType();
vehicleType.setType(modelCode);
vehicleLayout.setVehicleType(modelCode);
vehicleLayout.setFileName(FilenameUtils.removeExtension(FilenameUtils.getName(object.key())));
vehicleLayout.setS3BucketKey(object.key());
I know I missed something, but unable to figure it out.
You are creating a new VehicleType instance setting only the type field and set the vehicleType field of NonMsilVehicleLayout to that new instance. Since you specified CascadeType.ALL on NonMsilVehicleLayout#vehicleType, this means to Hibernate, that it has to persist the given VehicleType, because the instance has no primary key set.
I guess what you rather want is this code:
vehicleLayout.setVehicleType(
entitManager.createQuery("from VehicleType vt where vt.type = :type", VehicleType.class)
.setParameter("type", typeCode)
.getSingleResult()
);
This will load the VehicleType object by type and set that object on NonMsilVehicleLayout#vehicleType, which will then cause the foreign key column to be properly set to the primary key value.
Finally, after some workaround, I got the mistake, the column name attribute was incorrect, so I made it correct and remove the referencedColumn and Cascading.
Incorrect:
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name = "VEH_TYPE", referencedColumnName = "id")
private VehicleType vehicleType;
Correct:
#OneToOne
#JoinColumn(name = "VEHICLE_TYPE")
private VehicleType vehicleTypes;
also I have added the annotation #Column in the referende entity VehicleImage
public class VehicleType {
#Id
#Column(name = "ID") // added this one
private int id;
}
That bit workaround solved my problem, now I have achieved what I exactly looking for.
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).
I am using MySQL database.
In my table i there are two four primary keys, out of which one is auto incremented.
#Embeddable
public class EmployeeId implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Column(name = "id", nullable = false)//
This is just Pk in mysql table
**private int id;**
// I have tried and #GeneratedValue(strategy = GenerationType.IDENTITY),
#GeneratedValue(strategy = GenerationType.IDENTITY)
//and #GeneratedValue(strategy = GenerationType.TABLE)
//#GeneratedValue(strategy = GenerationType.AUTO, generator = "id") #SequenceGenerator(name = "id", sequenceName = "id")
**this is auto incremented and pk in mysql table**
#Column(name = "gender_key", nullable = false)
private int gender_key;
}
#Entity
#Table(name = "employee")
public class employee {
#EmbeddedId
private EmployeeId employeeId;
private String emp_name;
private String mobile_no;
employee() {
}}
public interface employeeRepository extends
JpaRepository<employee, EmployeeId> {
}
In My Controller I want id after employeeRepository.save(bean); method because i want to save that id in different db .
logger.info("gender_key is --- > "+gender_key);
But I am getting always 0 value of gender_key.
The thing which I have tried is:
bean = employeeRepository.save(bean)
int gender_key= bean.getGender_key();
logger.info("gender_keyis --- > "+gender_key);
But still the value for gender_key is 0(Zero).
Or any Query which I have to write in repository .
How I can get the auto incremented value of gender_key which is inserted into MySQL table?
Please Help.
Thanks in advance.
Your JPA #Id does not need to match the database PK column(s). So long as it is unique then that is all that matters.
From https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing:
The JPA Id does not always have to match the database table primary
key constraint, nor is a primary key or a unique constraint required.
As your an auto-increment column is guaranteed to be unique then just use gender_key as your #ID and map id as a normal column.
#Entity
#Table(name = "employee")
public class employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int genderKey;
#Column
private int id;
}
To be honest I would find your schema confusing however.
I would also suggest reading the following:
https://www.javatpoint.com/java-naming-conventions
You're missing a #GeneratedValue at the id field.
Depending on its values, you're free to choose a strategy for generation, like a sequences, id tables, an automatic internal id generation.
Last but not least GenerationType.AUTO will choose one of the mentioned strategies.
See the Javadocs for javax.persistence.GeneratedValue and javax.persistence.GenerationType.
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.
I am working on a web app and I am using JSF and JPA(EclipseLink). I have the tables story and story_translate, which are mapped as follows:
#Entity
#Table(name = "story")
public class Story{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
private String title;
private String description;
#OneToMany(mappedBy = "story", cascade=CascadeType.ALL)
private List<StoryTranslate> translateList;
//getters and setters
}
#Entity
#Table(name = "story_translate")
public class StoryTranslate{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
#Column(name="STORY_ID")
private Integer storyId;
#ManyToOne
#JoinColumn(name="story_id", referencedColumnName="id", updatable=false, insertable=false)
private Story story;
//some other fields, getters and setters
}
In a ManagedBean I am doing the following:
StoryTranslate translate = new StoryTranslate(null, sessionController.getEntity().getId(), getAuthUser().getId(), language,
title, description, new Date(), false);
EntityTransaction transaction = TransactionSingleton.getActiveInstance();
Story story = storyService.read(sessionController.getEntity().getId());
if (story != null){
if (story.getTranslateList() == null){
story.setTranslateList(new ArrayList<StoryTranslate>());
}
story.getTranslateList().add(translate);
translate.setStory(story);
}
transaction.commit();
When I try to create a new StoryTranslate, I get a DatabaseException, saying the story_id cannot be null.
I have managed relationships before, but I have never seen this error.
Where is the problem?
EDIT: I am sorry, but I have forgotten about another part of the mapping(must be the lack of sleep).
The problem is that your declare the storyId property in the StoryTranslate class for the STORY_ID column but when adding a new StoryTranslate , you do not set any value to its storyId property and I believe STORY_ID column has a NOT NULL constraint and that why you get the exception saying that story_id cannot be null.
The problem should be fixed once you set the storyId property of the StoryTranslate instance before committing the transaction .
But it is strange that you map the STORY_ID column to two different properties ( storyId and story) of the StoryTranslate class . Actually you do not need to declare storyId property as this value can be retrieved from the story instance . I suggest you change the mapping of StoryTranslate to the following and your code should work fine without any changes.
#Entity
#Table(name = "story_translate")
public class StoryTranslate{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
#ManyToOne
#JoinColumn(name="story_id")
private Story story;
//some other fields, getters and setters
}