My problem is as follows: When i create POST request in «Postman» app. This is what i try to POST
{"name": "John Doe", "email":"jdoe@test.com", "city": "London"}
I am getting the following error:
{
"timestamp": "2018-11-19T20:16:00.486+0000",
"status": 500,
"error": "Internal Server Error",
"message": "could not read a hi value - you need to populate the table: hibernate_sequence; nested exception is org.hibernate.id.IdentifierGenerationException: could not read a hi value - you need to populate the table: hibernate_sequence",
"path": "/api/ver01/product"
}
I was looking for answer in search box but none of them helped me. So i think that the problem is in sql code but I am not sure. Whole project is written in intelliJ IDE.
This is my Product class.
package com.hubertkulas.webstore.store.archetype;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.sql.Date;
@Entity
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private boolean contact;
private String email;
private String category;
private String name;
private String city;
private String model;
private BigDecimal price;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM-dd-yyyy")
private Date date;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public boolean isContact() {
return contact;
}
public void setContact(boolean contact) {
this.contact = contact;
}
public Long getId() {
return id;
}
// setter for id because Jackson will use it
public void setId(Long id) {
this.id = id;
}
}
This is my ProductController class
package com.hubertkulas.webstore.store.controllers;
import com.hubertkulas.webstore.store.archetype.Product;
import com.hubertkulas.webstore.store.jparepository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("api/ver01/product")
public class ProductController {
//injecting ProductRepository when ProductController is called
@Autowired
private ProductRepository productRepository;
@GetMapping
public List<Product> list() {
//finds all of the records and returns it
return productRepository.findAll();
}
@PostMapping
@ResponseStatus(HttpStatus.OK)
public void create(@RequestBody Product product){
productRepository.save(product);
}
@GetMapping("/{id}")
public Product get(@PathVariable("id") long id){
// return specific record with added id
return productRepository.getOne(id);
}
}
This is my ProductRepository Interface
package com.hubertkulas.webstore.store.jparepository;
import com.hubertkulas.webstore.store.archetype.Product;
import org.springframework.data.jpa.repository.JpaRepository;
//Using Jpa for CRUD operations
public interface ProductRepository extends JpaRepository<Product, Long> {
}
And this is my database
CREATE TABLE
product
(
id BIGINT NOT NULL,
contact BOOLEAN NOT NULL,
email VARCHAR,
category VARCHAR,
name VARCHAR,
city VARCHAR,
date DATETIME,
price NUMERIC,
model VARCHAR,
PRIMARY KEY (id)
);
CREATE TABLE
hibernate_sequence
(
next_val BIGINT
);
INSERT INTO product (id, contact, email, category, name, city, date, price)
VALUES (1, 1, 'abraham@site.com', 'Electronics', 'Abraham Westbrom', 'New
York', 4419619200000, '3250');
INSERT INTO product (id, contact, email, category, name, city, date, price)
VALUES (2, 1, 'udon@site.com', 'Electronics', 'Udon Hon', 'London',
4419619200000, '799');
INSERT INTO product (id, contact, email, category, name, city, date, price)
VALUES (3, 0, 'mateuszsinus@site.com', 'Software', 'Mateusz Sinus',
'Warsaw', 4419619200000, '10000');
INSERT INTO hibernate_sequence (next_val) VALUES (4);
I tried to upgrade hibernate from 4 to 5 in my project with spring 4.2
version. After this upgrade, I found the following error in my stack trace when I called a method for updating.
10:53:32,185 ERROR TableStructure:149 - could not read a hi value
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.hibernate_sequence' doesn't exist
I changed the auto incremented Id with annotation
@GeneratedValue(strategy=GenerationType.AUTO)
still the error remains.
thomasvdb
7291 gold badge10 silver badges31 bronze badges
asked Oct 6, 2015 at 11:13
2
You can also put :
@GeneratedValue(strategy = GenerationType.IDENTITY)
And let the DateBase manage the incrementation of the primary key:
AUTO_INCREMENT PRIMARY KEY
answered Mar 18, 2016 at 14:21
KikouKikou
1,8654 gold badges20 silver badges32 bronze badges
2
You need to set for Hibernate5.x <property name="hibernate.id.new_generator_mappings">false</property>
.. see and link.
For older version of hibernate 4.x:
<prop key="hibernate.id.new_generator_mappings">false</prop>
Om Sao
6,6882 gold badges40 silver badges61 bronze badges
answered Oct 6, 2015 at 11:44
rParvathirParvathi
1,9292 gold badges15 silver badges21 bronze badges
5
Working with Spring Boot
Solution
Put the string below in .application.properties
spring.jpa.properties.hibernate.id.new_generator_mappings=false
Explanation
On Hibernate 4.X this attribute defaults to true
.
answered Mar 28, 2018 at 18:43
RivanMotaRivanMota
7747 silver badges14 bronze badges
This is the reason behind this error:
It will look for how the database that you are using generates ids. For MySql or HSQSL, there are increment fields that automatically increment. In Postgres or Oracle, they use sequence tables. Since you didn’t specify a sequence table name, it will look for a sequence table named hibernate_sequence and use it for default. So you probably don’t have such a sequence table in your database and now you get that error.
answered Dec 28, 2016 at 3:14
1
FYI
If you are using hbm files to define the O/R mapping.
Notice that:
In Hibernate 5, the param name for the sequence name has been changed.
The following setting worked fine in Hibernate 4:
<generator class="sequence">
<param name="sequence">xxxxxx_seq</param>
</generator>
But in Hibernate 5, the same mapping setting file will cause a «hibernate_sequence doesn’t exist» error.
To fix this error, the param name must change to:
<generator class="sequence">
<param name="sequence_name">xxxxxx_seq</param>
</generator>
This problem wasted me 2, 3 hours.
And somehow, it looks like there are no document about it.
I have to read the source code of org.hibernate.id.enhanced.SequenceStyleGenerator to figure it out
answered Jun 21, 2016 at 9:18
Li YingLi Ying
2,18125 silver badges17 bronze badges
1
I was getting the same error «com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘mylocaldb.hibernate_sequence’ doesn’t exist».
Using spring mvc 4.3.7 and hibernate version 5.2.9, application is made using spring java based configuration. Now I have to add the hibernate.id.new_generator_mappings
property mentioned by @Eva Mariam in my code like this:
@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.addAnnotatedClasses(User.class);
return sessionBuilder.buildSessionFactory();
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.id.new_generator_mappings","false");
return properties;
}
And it worked like charm.
Clijsters
3,8581 gold badge29 silver badges37 bronze badges
answered Apr 18, 2017 at 5:12
Rajan ChauhanRajan Chauhan
4612 gold badges7 silver badges18 bronze badges
When you use
@GeneratedValue(strategy=GenerationType.AUTO)
or
@GeneratedValue
which is short hand way of the above, Hibernate starts to decide the best
generation strategy for you, in this case it has selected
GenerationType.SEQUENCE
as the strategy and that is why it is looking for
schemaName.hibernate_sequence
which is a table, for sequence based id generation.
When you use GenerationType.SEQUENCE
as the strategy you need to provide the @TableGenerator
as follows.
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "user_table_generator")
@TableGenerator(name = "user_table_generator",
table = "user_keys", pkColumnName = "PK_NAME", valueColumnName = "PK_VALUE")
@Column(name = "USER_ID")
private long userId;
When you set the strategy it the to
@GeneratedValue(strategy = GenerationType.IDENTITY)
.
original issue get resolved because then Hibernate stop looking for sequence table.
answered Sep 17, 2018 at 1:53
KalpaKalpa
3543 silver badges5 bronze badges
Just in case someone pulls their hair out with this problem like I did today, I couldn’t resolve this error until I changed
spring.jpa.hibernate.dll-auto=create
to
spring.jpa.properties.hibernate.hbm2ddl.auto=create
answered Feb 17, 2019 at 4:35
JMoneyJMoney
1712 silver badges6 bronze badges
1
in hibernate 5.x, you should add set hibernate.id.new_generator_mappings to false in hibernate.cfg.xml
<session-factory>
......
<property name="show_sql">1</property>
<property name="hibernate.id.new_generator_mappings">false</property>
......
</session-factory>
answered May 23, 2018 at 8:29
tekintiantekintian
2793 silver badges3 bronze badges
0
If you are using Hibernate version prior to Hibernate5 @GeneratedValue(strategy = GenerationType.IDENTITY)
works like a charm. But post Hibernate5 the following fix is necessary.
@Id
@GeneratedValue(strategy= GenerationType.AUTO,generator="native")
@GenericGenerator(name = "native",strategy = "native")
private Long id;
DDL
`id` BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY
REASON
Excerpt from hibernate-issue
Currently, if the hibernate.id.new_generator_mappings is set to false,
@GeneratedValue(strategy = GenerationType.AUTO) is mapped to native.
If this property is true (which is the defult value in 5.x), the
@GeneratedValue(strategy = GenerationType.AUTO) is always mapped to
SequenceStyleGenerator.For this reason, on any database that does not support sequences
natively (e.g. MySQL) we are going to use the TABLE generator instead
of IDENTITY.However, TABLE generator, although more portable, uses a separate
transaction every time a value is being fetched from the database. In
fact, even if the IDENTITY disables JDBC batch updates and the TABLE
generator uses the pooled optimizer, the IDENTITY still scales better.
answered Nov 7, 2019 at 19:08
You can also put :
@GeneratedValue(strategy = GenerationType.IDENTITY)
And let the DateBase manage the incrementation of the primary key:
AUTO_INCREMENT PRIMARY KEY
The above answer helped me.
Chris
2,93026 silver badges42 bronze badges
answered Dec 9, 2018 at 16:57
Step 1 : Entry into application.properties
spring.jpa.properties.hibernate.id.new_generator_mappings=false
Step 2 : Make sure the primary key column should be auto increment type
ALTER TABLE EMPLOYEES MODIFY COLUMN ID INT AUTO_INCREMENT;
answered May 12, 2021 at 5:28
JimmyJimmy
8637 silver badges17 bronze badges
This might be caused by HHH-10876 which got fixed so make sure you update to:
- Hibernate ORM 5.2.1,
- Hibernate ORM 5.1.1,
- Hibernate ORM 5.0.11
answered Nov 18, 2017 at 17:28
Vlad MihalceaVlad Mihalcea
136k69 gold badges543 silver badges887 bronze badges
1
I added Hibernate sequence in postgres.
Run this query in PostGres Editor:
CREATE SEQUENCE hibernate_sequence
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 2
CACHE 1;
ALTER TABLE hibernate_sequence
OWNER TO postgres;
I will find out the pros/cons of using the query but for someone who need help can use this.
answered May 18, 2018 at 14:27
ChinmoyChinmoy
1,30612 silver badges14 bronze badges
In my case, replacing all annotations GenerationType.AUTO
by GenerationType.SEQUENCE
solved the issue.
answered Apr 26, 2019 at 17:12
CREATE TABLE hibernate_sequence
(
next_val
bigint DEFAULT NULL
) ;
insert into hibernate_sequence
values (1);
answered Sep 8, 2022 at 14:43
Run this query
create sequence hibernate_sequence start with 1 increment by 1
answered May 21, 2019 at 9:03
1
Я попытался обновить hibernate с 4 до 5 в моем проекте с spring 4.2
версия. После этого обновления я обнаружил следующую ошибку в трассировке стека, когда я вызвал метод для обновления.
10:53:32,185 ERROR TableStructure:149 - could not read a hi value
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.hibernate_sequence' doesn't exist
Я изменил автоматический увеличенный идентификатор с аннотацией
@GeneratedValue(strategy=GenerationType.AUTO)
тем не менее ошибка остается.
962
10
10 ответов:
вы также можете поместить :
@GeneratedValue(strategy = GenerationType.IDENTITY)
и пусть DateBase управляет приращением первичного ключа:
AUTO_INCREMENT PRIMARY KEY
необходимо указать
<prop key="hibernate.id.new_generator_mappings">false</prop>
.. смотрите ссылке и ссылке.
работа с Spring Boot
поместите строку ниже .приложение.свойства
решение
spring.jpa.properties.hibernate.id.new_generator_mappings=false
объяснение
На Hibernate 4.X этот атрибут по умолчанию имеет значение
true
.
Я получал ту же ошибку «com.mysql.интерфейс jdbc.исключения.jdbc4.MySQLSyntaxErrorException: таблица ‘ mylocaldb.hibernate_sequence’ не существует».
используя spring mvc 4.3.7 и hibernate версии 5.2.9, приложение сделано с использованием конфигурации на основе spring java. Теперь я должен добавить
hibernate.id.new_generator_mappings
свойство упоминается @Eva Mariam в моем коде следующим образом:@Autowired @Bean(name = "sessionFactory") public SessionFactory getSessionFactory(DataSource dataSource) { LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource); sessionBuilder.addProperties(getHibernateProperties()); sessionBuilder.addAnnotatedClasses(User.class); return sessionBuilder.buildSessionFactory(); } private Properties getHibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.show_sql", "true"); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); properties.put("hibernate.id.new_generator_mappings","false"); return properties; }
и он работал как шарм.
Это причина этой ошибки:
Это будет выглядеть как база данных, которую вы используете генерирует идентификаторы. Для MySql или HSQSL существуют поля инкремента, которые автоматически увеличиваются. В Postgres или Oracle они используют таблицы последовательностей. Поскольку вы не указали имя таблицы последовательности, она будет искать таблицу последовательности с именем hibernate_sequence и использовать ее по умолчанию. Поэтому у вас, вероятно, нет такой таблицы последовательности в вашей базе данных, и теперь вы получаете эту ошибку.
FYI
Если вы используете файлы hbm для определения отображения O/R.
обратите внимание, что:
В Hibernate 5, имя параметра для имени последовательности было изменено.
следующая настройка работала нормально в Hibernate 4:
<generator class="sequence"> <param name="sequence">xxxxxx_seq</param> </generator>
а в Hibernate 5, тот же файл настройки сопоставления вызовет ошибку «hibernate_sequence не существует».
чтобы исправить эту ошибку, параметр имя надо менять to:
<generator class="sequence"> <param name="sequence_name">xxxxxx_seq</param> </generator>
эта проблема потратила меня 2, 3 часа.
и как-то, похоже, есть документ об этом.
мне нужно читать исходный код орг.гибернации.ИД.усиливается.SequenceStyleGenerator, чтобы понять это
в спящем режиме 5.x, вы должны добавить set hibernate.id.new_generator_mappings к false в hibernate.контекстно-свободная грамматика.xml
<session-factory> ...... <property name="show_sql">1</property> <property name="hibernate.id.new_generator_mappings">false</property> ...... </session-factory>
Это может быть вызвано HHH-10876 который был исправлен, поэтому убедитесь, что вы обновляете:
- Hibernate ORM 5.2.1,
- Hibernate ORM 5.1.1,
- Hibernate ORM 5.0.11
Я добавил последовательность гибернации в postgres.
Запустите этот запрос в Редакторе PostGres:CREATE SEQUENCE hibernate_sequence INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 2 CACHE 1; ALTER TABLE hibernate_sequence OWNER TO postgres;
я узнаю плюсы / минусы использования запроса, но для тех, кто нуждается в помощи, может использовать это.
при использовании
@GeneratedValue(strategy=GenerationType.AUTO)
или
@GeneratedValue
что короткий путь руки вышеуказанного, спящий режим начинает решать самое лучшее
стратегия генерации для вас, в данном случае она выбрала
GenerationType.SEQUENCE
как стратегия и именно поэтому он ищет
schemaName.hibernate_sequence
который представляет собой таблицу для генерации идентификаторов на основе последовательности.при использовании
GenerationType.SEQUENCE
в качестве стратегии вам нужно предоставить@TableGenerator
следующим образом.@Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "user_table_generator") @TableGenerator(name = "user_table_generator", table = "user_keys", pkColumnName = "PK_NAME", valueColumnName = "PK_VALUE") @Column(name = "USER_ID") private long userId;
когда вы устанавливаете стратегию это в
@GeneratedValue(strategy = GenerationType.IDENTITY)
.исходная проблема будет решена, потому что затем Hibernate перестанет искать таблицу последовательности.
I use oracle9i to store information,my
Code:
<class name=»events.Event» table=»EVENTS»>
<id name=»id» column=»EVENT_ID»>
<generator class=»hilo»>
<param name=»table»>test</param>
<param name=»column»>next_value</param>
<param name=»max_lo»>100</param>
</generator>
</id>
<property name=»date» type=»timestamp» column=»EVENT_DATE»/>
<property name=»title»/>
</class>
My table is follows:
SQL> desc test
Name Type
————————————
NEXT_VALUE NUMBER(38)
SQL> desc events;
Name Type
————————————-
EVENT_ID NUMBER(19)
EVENT_DATE TIMESTAMP(6)
TITLE VARCHAR2(255 CHAR)
When I run my code,it raise following error:
Exception in thread «main» org.hibernate.id.IdentifierGenerationException: could not read a hi value — you need to populate the table: test
at org.hibernate.id.TableGenerator.doWorkInCurrentTransaction(TableGenerator.java:138)
at org.hibernate.engine.TransactionHelper$1Work.doWork(TransactionHelper.java:38)
at org.hibernate.engine.transaction.Isolater$JdbcDelegate.delegateWork(Isolater.java:187)
at org.hibernate.engine.transaction.Isolater.doIsolatedWork(Isolater.java:43)
at org.hibernate.engine.TransactionHelper.doWorkInNewTransaction(TransactionHelper.java:51)
at org.hibernate.id.TableGenerator.generate(TableGenerator.java:94)
at org.hibernate.id.TableHiLoGenerator.generate(TableHiLoGenerator.java:62)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId
(AbstractSaveEventListener.java:99)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGene
ratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrR
equestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTran
sient(DefaultSaveOrUpdateEventListener.java:172)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(
DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtection
Wrapper.invoke(ThreadLocalSessionContext.java:301)
at $Proxy0.save(Unknown Source)
at events.EventManager.createAndStoreEvent(EventManager.java:40)
at events.EventManager.main(EventManager.java:10)
I guess I may create table wrong test,maybe miss some columns,but I don’t know how to do it.Anybody could tell me how to do it?
Thanks
Edward
Problem
Using SQL Server database, after migrating databases or restoring sql dumps under certain conditions, the following appears in the atlassian-confluence.log
:
2009-06-02 14:26:42,223 ERROR [DefaultQuartzScheduler_Worker-1] [sf.hibernate.id.TableGenerator] generate could not read a hi value
java.sql.SQLException: Invalid object name 'hibernate_unique_key'.
at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:365)
at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2781)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2224)
at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:628)
at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:418)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:693)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at net.sf.hibernate.id.TableGenerator.generate(TableGenerator.java:94)
at com.atlassian.hibernate.ResettableTableHiLoGenerator.generate(ResettableTableHiLoGenerator.java:62)
...
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy55.verify(Unknown Source)
at com.atlassian.confluence.cluster.safety.ClusterSafetyJob.executeJob(ClusterSafetyJob.java:13)
at com.atlassian.confluence.setup.quartz.AbstractClusterAwareQuartzJobBean.surroundJobExecutionWithLogging(AbstractClusterAwareQuartzJobBean.java:64)
...
Causes
- The SQL Server database was created or recreated with tables with the incorrect case, either capital or lower-case.
- The schema name of Confluence database is not the default schema name which is
dbo
(MS SQL Server). - The hibernate_unique_key table is empty and the next_hi column has a null value in it.
Resolution
- Check Database Setup for SQL Server to ensure that collation and case-sensitivity is configured correctly.
- Contact your database administrators and request to change the schema name to
dbo
. For reference see this link. -
Run the following query to confirm if the table is populated:
SELECT max(next_hi) FROM hibernate_unique_key;
If it returns a null instead of a numeric value, shut down you instance and run the following query:
insert into hibernate_unique_key (next_hi) values (0);
Last modified on Jun 1, 2016
Related content
- No related content found
My problem is as follows: When i create POST quotes uvdos java request in «Postman» app. This is what i try quotes uvdos java to POST
{"name": "John Doe", "email":"jdoe@test.com", "city": "London"}
I am getting the following error:
{
"timestamp": "2018-11-19T20:16:00.486+0000",
"status": 500,
"error": "Internal Server Error",
"message": "could not read a hi value - you need to populate the table: hibernate_sequence; nested exception is org.hibernate.id.IdentifierGenerationException: could not read a hi value - you need to populate the table: hibernate_sequence",
"path": "/api/ver01/product"
}
I was looking for answer in search box but quotes uvdos java none of them helped me. So i think that the quotes uvdos java problem is in sql code but I am not sure. quotes uvdos java Whole project is written in intelliJ IDE.
This is my Product class.
package com.hubertkulas.webstore.store.archetype;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.sql.Date;
@Entity
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private boolean contact;
private String email;
private String category;
private String name;
private String city;
private String model;
private BigDecimal price;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM-dd-yyyy")
private Date date;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public boolean isContact() {
return contact;
}
public void setContact(boolean contact) {
this.contact = contact;
}
public Long getId() {
return id;
}
// setter for id because Jackson will use it
public void setId(Long id) {
this.id = id;
}
}
This is my ProductController class
package com.hubertkulas.webstore.store.controllers;
import com.hubertkulas.webstore.store.archetype.Product;
import com.hubertkulas.webstore.store.jparepository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("api/ver01/product")
public class ProductController {
//injecting ProductRepository when ProductController is called
@Autowired
private ProductRepository productRepository;
@GetMapping
public List<Product> list() {
//finds all of the records and returns it
return productRepository.findAll();
}
@PostMapping
@ResponseStatus(HttpStatus.OK)
public void create(@RequestBody Product product){
productRepository.save(product);
}
@GetMapping("/{id}")
public Product get(@PathVariable("id") long id){
// return specific record with added id
return productRepository.getOne(id);
}
}
This is my ProductRepository Interface
package com.hubertkulas.webstore.store.jparepository;
import com.hubertkulas.webstore.store.archetype.Product;
import org.springframework.data.jpa.repository.JpaRepository;
//Using Jpa for CRUD operations
public interface ProductRepository extends JpaRepository<Product, Long> {
}
And this is my database
CREATE TABLE
product
(
id BIGINT NOT NULL,
contact BOOLEAN NOT NULL,
email VARCHAR,
category VARCHAR,
name VARCHAR,
city VARCHAR,
date DATETIME,
price NUMERIC,
model VARCHAR,
PRIMARY KEY (id)
);
CREATE TABLE
hibernate_sequence
(
next_val BIGINT
);
INSERT INTO product (id, contact, email, category, name, city, date, price)
VALUES (1, 1, 'abraham@site.com', 'Electronics', 'Abraham Westbrom', 'New
York', 4419619200000, '3250');
INSERT INTO product (id, contact, email, category, name, city, date, price)
VALUES (2, 1, 'udon@site.com', 'Electronics', 'Udon Hon', 'London',
4419619200000, '799');
INSERT INTO product (id, contact, email, category, name, city, date, price)
VALUES (3, 0, 'mateuszsinus@site.com', 'Software', 'Mateusz Sinus',
'Warsaw', 4419619200000, '10000');
INSERT INTO hibernate_sequence (next_val) VALUES (4);
25
Answers 1 : of message -could not read a hi value — you need to populate the table: hibernate_sequence
If you are creating a schema using query uvdos hibernate spring boot for local database and jpa query uvdos hibernate is configured to do a auto create-drop, query uvdos hibernate ideally you wont be facing this query uvdos hibernate situation.
spring.jpa.hibernate.ddl-auto=create-drop
But in staging/production you want to query uvdos hibernate handle your schema definition (DDL) query uvdos hibernate separately so hibernate_sequence needs query uvdos hibernate to have an initial value and 0 should query uvdos hibernate suffice for start. It tells the program query uvdos hibernate library from which number to start the query uvdos hibernate auto-generation id.
spring.jpa.hibernate.ddl-auto=validate
INSERT INTO <schema_name>.hibernate_sequence (next_val) VALUES (0);
The above one works for MYSQL
0
2023-02-06T13:03:10+00:00 2023-02-06T13:03:10+00:00Answer Link
mRahman
posted 5 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Hi,
I am facing same issues while upgrading hibernate version to 5.0. Hibernate is using SequenceStyleGenerator and giving error-
ERROR org.hibernate.id.enhanced.TableStructure — could not read a hi value
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name ‘hibernate_sequence’.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:285)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:353)
at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:224)
at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46)
at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:139)
at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:126)
at org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55)
at org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:56)
at org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:412)
at org.hibernate.collection.internal.PersistentIdentifierBag.preInsert(PersistentIdentifierBag.java:375)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1264)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:50)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1282).
..
We are not using annotations. Current version is 3.6. I migrated to 4.3 and faced no issues. Using SQLServer2012. Setting my configurations in the code like this —
…
…
c.setProperty(«hibernate.dialect», SQLServer2012Dialect.class.getName());
c.setProperty(«hibernate.id.new_generator_mappings», «false»);
c.configure(«hibernate.cfg.xml»); //hibernate.cfg.xml has all mapping resources
this.sessionFactory = c.buildSessionFactory();
I did not have to set hibernate.id.new_generator_mappings to false for version 4.3. But with hibernate version 5.0.9 this setting is not working. When I debugged, hibernate is using SequenceGenerator for older versions but it is using SequenceStyleGenerator for 5.0.9. Can you please advise.
I am using SEQUENCE.
Thanks