This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I tried adding new class to my application. Everything was fine, until I added Boolean read. When I add it to my class, I get:
We got the following error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'read tinyint(1) default 0, constraint ck_event_type check (' at line 7 [ERROR:1064, SQLSTATE:42000], while trying to run this SQL script:
and the important part of the script:
create table event (
id bigint auto_increment not null,
type varchar(14) not null,
user_id bigint,
message varchar(255) not null,
date date,
read tinyint(1) default 0,
constraint ck_event_type check (type in ('game_started','game_completed','wrong_answer','correct_answer','wrong_location')),
constraint pk_event primary key (id))
I have no idea what's the problem. I have Boolean declared in other class and there is no problem. I'm using play 2.2.1
My class:
package models;
import java.sql.Date;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
import com.avaje.ebean.*;
import play.data.validation.Constraints.*;
#Entity
public class Event extends Model{
#Id
public Long id;
#Enumerated(EnumType.STRING)
#Column(nullable = false)
public EVENT_TYPE type;
#ManyToOne
public User user;
#Column
public Date date;
#Column(nullable = false)
public String message;
#Column
public Boolean read;
public Event(User user, String message, EVENT_TYPE type, Date date) {
//this.user = user;
//this.message = message;
//this.type = type;
//this.date = date;
//read = false;
}
}
read is a reserved keyword in MySql. Try naming that column something else.
Reserved Words in MySQL 5.7
Related
I have this error:
duplicate key value violates unique constraint "HDPL_COMPOSANT_pkey"
Détail : Key (composant_id)=(766975) already exists.
nextVal is superior to MAX(composantId) so why does it show this error?
#Entity
#Table(name= ""HDPL_COMPOSANT"",schema="hdpl")
public class ComposantEntity implements java.io.Serializable {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="composant_id2")
#SequenceGenerator(
name="composant_id2",
sequenceName="\"HDPL_COMPOSANT_composant_id_seq\""
)
#Column(name="composant_id", unique=true, nullable=false)
private int composantId;
#Column(name="code_app", nullable=false)
private String codeApp;
#Column(name="libelle_app", nullable=false)
private String libelleApp;
#Transient
private String typeModule;
CREATE SEQUENCE HDPL_COMPOSANT_composant_id_seq;
CREATE TABLE hdpl."HDPL_COMPOSANT"
(
code_app character varying COLLATE pg_catalog."default" NOT NULL,
libelle_app character varying COLLATE pg_catalog."default" NOT NULL,
composant_id integer NOT NULL default nextval ('HDPL_COMPOSANT_composant_id_seq'::regclass),
CONSTRAINT hdpl_composant_pk PRIMARY KEY (composant_id)
) WITHOUT OIDS;
It crashes when i call this method
#Override
public void createComposant(String codeApp, String libelleApp) {
ComposantEntity composantEntity = new ComposantEntity();
composantRepo.deleteByCodeAppAndLibelleApp(codeApp, libelleApp);
composantEntity.setCodeApp(codeApp);
composantEntity.setLibelleApp(libelleApp);
composantRepo.save(composantEntity);
}
when i try to save my composantEntity it crashes showing the error above
My question is why my Id doesnt take nextVal and take an other value that already exists
am trying to migrate to JPA this method here s the ancient code that i tried to change using the method above
#Override
#MethodLog(logLevel = StandardLevel.DEBUG)
public long createComposant(String codeApp, String libelleApp) {
final KeyHolder idHolder = new GeneratedKeyHolder();
final SqlParameterSource params = new MapSqlParameterSource().addValue(CODE_APP, codeApp).addValue(LIBELLE_APP,
libelleApp);
// suppression des anciens
jdbcTemplate.update(DELETE_COMPOSANT, params);
// creation des nouveaux
jdbcTemplate.update(CREATE_COMPOSANT, params, idHolder, new String[] { "composant_id" });
return idHolder.getKey().longValue();
}
I created a database with sqflite in Flutter. When I try to insert data I get the error
error DatabaseException(near ")": syntax error (code 1 SQLITE_ERROR): , while compiling: CREATE TABLE nutritionTable(
_id INTEGER PRIMARY KEY,
calories INTEGER NOT NULL,
carbs INTEGER NOT NULL,
fat INTEGER NOT NULL,
protein INTEGER NOT NULL,
))
My code to create a table looks like this:
static final _dbName = 'userNutritionSql.db';
static final _dbVersion = 1;
static final _tableName = 'nutritionTable';
static final columnId = '_id';
static final columnCalories = 'calories';
static final columnCarbs = 'carbs';
static final columnFat = 'fat';
static final columnProtein = 'protein';
Future _onCreate(Database db, int version) async{
final idType = 'INTEGER PRIMARY KEY';
final intType = 'INTEGER NOT NULL';
await db.execute(
'''
CREATE TABLE $_tableName(
$columnId $idType,
$columnCalories $intType,
$columnCarbs $intType,
$columnFat $intType,
$columnProtein $intType,
)
'''
);
}
I cant spot the syntax error, does anyone has an idea whats wrong?
I´m trying to use Optimistic Locking with Micronaut Data and Kotlin, but unfortunately it fails with the Exception:
14:33:32.113 [default-nioEventLoopGroup-1-2] ERROR i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: An error occurred invoking pre-persist event listeners: Unsupported #Version type: long
io.micronaut.data.event.PersistenceEventException: An error occurred invoking pre-persist event listeners: Unsupported #Version type: long
at io.micronaut.data.runtime.event.EntityEventRegistry.prePersist(EntityEventRegistry.java:92)
at io.micronaut.data.hibernate.event.EventIntegrator.lambda$integrate$9d2e46a6$1(EventIntegrator.java:77)
at org.hibernate.action.internal.EntityInsertAction.preInsert(EntityInsertAction.java:227)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:100)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1362)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:453)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3212)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2380)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
...
My setup looks like this (should be pretty much like the docs):
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.EnumType
import javax.persistence.Enumerated
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.Table
import javax.persistence.Version
#Entity
#Table(name = "invoice_queue")
data class InvoiceQueueEntity(
#Id
#GeneratedValue
var id: Long = 0,
...(things left out for privacy reasons)...
#Version
var version: Long = 0L,
)
The migrations creating the table are:
create table invoice_queue
(
id int8 not null,
primary key (id)
);
create sequence hibernate_sequence start 1 increment 1;
alter table if exists invoice_queue
add column version int8 not null default 0;
Am I missing something?
If you are sure that you are using javax.persistence.Version and not io.micronaut.core.version.annotation.Version, then the problem is probably that the java field has a primitive type.
If you make it nullable, you should get the boxed type. Try:
var version: Long? = 0L
Question
Why I get NULL not allowed for column "ID" exception when I execute INSERT INTO PUBLIC.MY_ENTITY (name) VALUES ('test name');?
Setup
I'm using Spring Boot and Hibernate. Spring Boot is launched with properties:
hibernate.hbm2ddl.auto=update
spring.jpa.hibernate.ddl-auto=update
I have entity:
#Entity
#Table(name = "MY_ENTITY")
public class MyEntity {
#Id
#SequenceGenerator(sequenceName = "MY_ENTITY_SEQ", name = "MyEntitySeq")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MyEntitySeq")
private Long id;
#Column(unique = true, nullable = false)
private String name;
// getters & setters
// ...
}
Table has been generated on application start.
I can prove that sequence has been created with the next query:
SELECT * FROM INFORMATION_SCHEMA.SEQUENCES WHERE SEQUENCE_NAME = 'MY_ENTITY_SEQ'
P.S.
For some reason Hibernate does not link sequence to id auto generation. I can solve the problem with the query below. But how make Hibernate generate the query below?
ALTER TABLE PUBLIC.MY_ENTITY ALTER COLUMN ID BIGINT DEFAULT (NEXT VALUE FOR PUBLIC.MY_ENTITY_SEQ) NOT NULL NULL_TO_DEFAULT SEQUENCE PUBLIC.MY_ENTITY_SEQ;
INSERT INTO PUBLIC.MY_ENTITY (name) VALUES ('test name');
Give the #SequenceGenerator an allocationSize: #SequenceGenerator(sequenceName = "MY_ENTITY_SEQ", name = "MyEntitySeq", allocationSize=1)
Check the dialect you are using
Set "hibernate.id.new_generator_mappings" to "true"
When running a particular unit-test, I am getting the exception:
Caused by: org.hibernate.HibernateException: Errors in named queries: UPDATE_NEXT_FIRE_TIME
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:437)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1385)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:954)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:891)
... 44 more
for the named query defined here:
#Entity(name="fireTime")
#Table(name="qrtz_triggers")
#NamedQueries({
#NamedQuery(
name="UPDATE_NEXT_FIRE_TIME",
query= "update fireTime t set t.next_fire_time = :epochTime where t.trigger_name = 'CalculationTrigger'")
})
public class JpaFireTimeUpdaterImpl implements FireTimeUpdater {
#Id
#Column(name="next_fire_time", insertable=true, updatable=true)
private long epochTime;
public JpaFireTimeUpdaterImpl() {}
public JpaFireTimeUpdaterImpl(final long epochTime) {
this.epochTime = epochTime;
}
#Override
public long getEpochTime() {
return this.epochTime;
}
public void setEpochTime(final long epochTime) {
this.epochTime = epochTime;
}
}
After debugging as deep as I could, I've found that the exception occurs in w.statement(hqlAst) in QueryTranslatorImpl:
private HqlSqlWalker analyze(HqlParser parser, String collectionRole) throws QueryException, RecognitionException {
HqlSqlWalker w = new HqlSqlWalker( this, factory, parser, tokenReplacements, collectionRole );
AST hqlAst = parser.getAST();
// Transform the tree.
w.statement( hqlAst );
if ( AST_LOG.isDebugEnabled() ) {
ASTPrinter printer = new ASTPrinter( SqlTokenTypes.class );
AST_LOG.debug( printer.showAsString( w.getAST(), "--- SQL AST ---" ) );
}
w.getParseErrorHandler().throwQueryException();
return w;
}
Is there something wrong with my query or annotations?
NamedQuery should be written with JPQL, but query seems to mix both names of persistent attributes and names of database columns. Names of database columns cannot be used in JPQL.
In this case instead of next_fire_time name of the persistent attribute epochTime should be used. Also trigger_name looks more like name of the database column than name of the persistent attribute, but it seems not to be mapped in your current class at all. After it is mapped, query is as follows:
update fireTime t set t.epochTime = :epochTime
where t.triggerName = 'CalculationTrigger'
If SQL query is preferred, then #NamedNativeQuery should be used instead.
As a side note, JPA 2.0 specification doesn't encourage changing primary key:
The application must not change the value of the primary key[10]. The
behavior is undefined if this occurs.[11]
In general entities are not aware of changed made via JPQL queries. That gets especially interesting when trying to refresh entity that does not exist anymore (because primary key was changed).
Additionally naming is little bit confusing:
Name of the class looks more like name of the service class
than name of the entity.
Starting name of the entity with lower
case letter is rather rare style.
Name of the entity, name of the
table and name of the class do not match too well.