#java #mysql #spring-boot #jpa #spring-data-jpa
Вопрос:
Я получаю «Индекс параметров вне диапазона (4 gt; количество параметров, равное 3)». при вставке объектов в базу данных с помощью spring data JPA. Ниже приведен мой код:
package com.shree.testjpa.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "city") @Data @AllArgsConstructor @NoArgsConstructor public class City implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; @Column(name = "country_name") private String countryName; }
==
package com.shree.testjpa.entity; import javax.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Entity @Table(name = "company") @Data @AllArgsConstructor @NoArgsConstructor public class Company implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; @Column(name = "country_name") private String countryName; }
==
package com.shree.testjpa.entity; import java.io.Serializable; import java.util.List; import javax.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Table(name = "person") @Data @AllArgsConstructor @NoArgsConstructor public class Person implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; private int age; @Column(name = "country_name") private String countryName; @OneToMany(cascade = { CascadeType.MERGE }, fetch = FetchType.EAGER) @JoinTable(name = "person_city_company", joinColumns = { @JoinColumn(table = "person", name = "person_id", referencedColumnName = "id", insertable = false, updatable = false), @JoinColumn(table = "person", name = "country_name", referencedColumnName = "country_name", insertable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(table = "city", name = "city_id", referencedColumnName = "id", insertable = false, updatable = false), @JoinColumn(table = "city", name = "country_name", referencedColumnName = "country_name", insertable = false, updatable = false) }) private Listlt;Citygt; stayed; }
==
package com.shree.testjpa.repo; import com.shree.testjpa.entity.City; import org.springframework.data.jpa.repository.JpaRepository; public interface CityRepository extends JpaRepositorylt;City, Longgt;{ }
==
package com.shree.testjpa.repo; import com.shree.testjpa.entity.Company; import org.springframework.data.jpa.repository.JpaRepository; public interface CompanyRepository extends JpaRepositorylt;Company, Longgt;{ }
==
package com.shree.testjpa.repo; import com.shree.testjpa.entity.Person; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface PersonRepo extends JpaRepositorylt;Person, Longgt;{ }
==
package com.shree.testjpa; import java.util.ArrayList; import java.util.List; import com.shree.testjpa.entity.City; import com.shree.testjpa.entity.Person; import com.shree.testjpa.repo.CityRepository; import com.shree.testjpa.repo.CompanyRepository; import com.shree.testjpa.repo.PersonRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class TestService { @Autowired PersonRepo personRepo; @Autowired CityRepository cityRepository; @Autowired CompanyRepository compoCompanyRepository; public void initTables() { //Listlt;Citygt; cityList = new ArrayListlt;gt;(); //cityList.add(new City(0, "Gargoti", "India")); //cityList.add(new City(0, "Delhi", "India")); //cityList.add(new City(0, "Kolhapur", "India")); //cityList.add(new City(0, "Pune", "India")); Listlt;Citygt; cityList = cityRepository.findAll(); Listlt;Persongt; people = new ArrayListlt;gt;(); people.add(new Person(0, "Shrirang", 25, "India", cityList)); //people.add(new Person(0, "Bhagwat", 25, "India", cityList.subList(1,2))); personRepo.saveAll(people); } public void printTables(){ System.out.println(personRepo.findAll()); } }
===
package com.shree.testjpa; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TestJpaApplication implements CommandLineRunner { @Autowired private TestService testService; public static void main(String[] args) { SpringApplication.run(TestJpaApplication.class, args); } @Override public void run(String... args) throws Exception { //testService.printTables(); testService.initTables(); } }
== application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?autoReconnect=true spring.datasource.username=root spring.datasource.password= spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect # drop n create table, good for testing, comment this in production #spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true #spring.jpa.properties.hibernate.show-sql=true spring.jpa.properties.hibernate.format_sql=true
==
lt;?xml version="1.0" encoding="UTF-8"?gt; lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"gt; lt;modelVersiongt;4.0.0lt;/modelVersiongt; lt;parentgt; lt;groupIdgt;org.springframework.bootlt;/groupIdgt; lt;artifactIdgt;spring-boot-starter-parentlt;/artifactIdgt; lt;versiongt;2.6.0lt;/versiongt; lt;relativePath/gt; lt;!-- lookup parent from repository --gt; lt;/parentgt; lt;groupIdgt;com.shree.testjpalt;/groupIdgt; lt;artifactIdgt;test-jpalt;/artifactIdgt; lt;versiongt;0.0.1-SNAPSHOTlt;/versiongt; lt;namegt;test-jpalt;/namegt; lt;descriptiongt;Demo project for Spring Bootlt;/descriptiongt; lt;propertiesgt; lt;java.versiongt;8lt;/java.versiongt; lt;/propertiesgt; lt;dependenciesgt; lt;dependencygt; lt;groupIdgt;org.springframework.bootlt;/groupIdgt; lt;artifactIdgt;spring-boot-starter-data-jpalt;/artifactIdgt; lt;/dependencygt; lt;dependencygt; lt;groupIdgt;mysqllt;/groupIdgt; lt;artifactIdgt;mysql-connector-javalt;/artifactIdgt; lt;scopegt;runtimelt;/scopegt; lt;/dependencygt; lt;dependencygt; lt;groupIdgt;org.projectlomboklt;/groupIdgt; lt;artifactIdgt;lomboklt;/artifactIdgt; lt;optionalgt;truelt;/optionalgt; lt;/dependencygt; lt;dependencygt; lt;groupIdgt;org.springframework.bootlt;/groupIdgt; lt;artifactIdgt;spring-boot-starter-testlt;/artifactIdgt; lt;scopegt;testlt;/scopegt; lt;/dependencygt; lt;/dependenciesgt; lt;buildgt; lt;pluginsgt; lt;plugingt; lt;groupIdgt;org.springframework.bootlt;/groupIdgt; lt;artifactIdgt;spring-boot-maven-pluginlt;/artifactIdgt; lt;configurationgt; lt;excludesgt; lt;excludegt; lt;groupIdgt;org.projectlomboklt;/groupIdgt; lt;artifactIdgt;lomboklt;/artifactIdgt; lt;/excludegt; lt;/excludesgt; lt;/configurationgt; lt;/plugingt; lt;/pluginsgt; lt;/buildgt; lt;/projectgt;
== MySql SQL with sample data: =======
DROP TABLE IF EXISTS `City`; CREATE TABLE `City` ( `id` bigint NOT NULL AUTO_INCREMENT, `name` varchar(45) DEFAULT NULL, `country_name` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; LOCK TABLES `City` WRITE; INSERT INTO `City` VALUES (1,'Gargoti','India'),(2,'Kolhapur','India'); UNLOCK TABLES; DROP TABLE IF EXISTS `Company`; CREATE TABLE `Company` ( `id` bigint NOT NULL AUTO_INCREMENT, `name` varchar(45) DEFAULT NULL, `country_name` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; LOCK TABLES `Company` WRITE; UNLOCK TABLES; DROP TABLE IF EXISTS `Person`; CREATE TABLE `Person` ( `id` bigint NOT NULL AUTO_INCREMENT, `name` varchar(45) DEFAULT NULL, `age` int DEFAULT NULL, `country_name` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; LOCK TABLES `Person` WRITE; INSERT INTO `Person` VALUES (8,'Shrirang',25,'India'); UNLOCK TABLES; DROP TABLE IF EXISTS `person_city_company`; CREATE TABLE `person_city_company` ( `id` bigint NOT NULL AUTO_INCREMENT, `person_id` bigint NOT NULL, `city_id` bigint NOT NULL, `company_id` bigint NOT NULL, `country_name` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; LOCK TABLES `person_city_company` WRITE; INSERT INTO `person_city_company` VALUES (1,8,1,-1,'India'),(2,8,2,-1,'India'); UNLOCK TABLES;
== Исключение:
. ____ _ __ _ _ /\ / ___'_ __ _ _(_)_ __ __ _ ( ( )___ | '_ | '_| | '_ / _` | \/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |___, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.6.0) 2021-11-26 13:28:02.696 INFO 3971 --- [ main] com.shree.testjpa.TestJpaApplication : Starting TestJpaApplication using Java 11.0.11 on admins-MacBook-Pro.local with PID 3971 (/Volumes/CodeDrive/authmvp/authmvpwps/test-jpa/target/classes started by skumbhar in /Volumes/CodeDrive/authmvp/authmvpwps/test-jpa) 2021-11-26 13:28:02.697 INFO 3971 --- [ main] com.shree.testjpa.TestJpaApplication : No active profile set, falling back to default profiles: default 2021-11-26 13:28:03.049 INFO 3971 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2021-11-26 13:28:03.123 INFO 3971 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 65 ms. Found 3 JPA repository interfaces. 2021-11-26 13:28:03.467 INFO 3971 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2021-11-26 13:28:03.840 INFO 3971 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2021-11-26 13:28:03.890 INFO 3971 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] 2021-11-26 13:28:03.944 INFO 3971 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.1.Final 2021-11-26 13:28:04.098 INFO 3971 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final} 2021-11-26 13:28:04.178 INFO 3971 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect 2021-11-26 13:28:04.627 INFO 3971 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] 2021-11-26 13:28:04.636 INFO 3971 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2021-11-26 13:28:05.013 INFO 3971 --- [ main] com.shree.testjpa.TestJpaApplication : Started TestJpaApplication in 7.64 seconds (JVM running for 8.112) 2021-11-26 13:28:05.134 DEBUG 3971 --- [ main] org.hibernate.SQL : select city0_.id as id1_0_, city0_.country_name as country_2_0_, city0_.name as name3_0_ from city city0_ Hibernate: select city0_.id as id1_0_, city0_.country_name as country_2_0_, city0_.name as name3_0_ from city city0_ 2021-11-26 13:28:05.198 DEBUG 3971 --- [ main] org.hibernate.SQL : insert into person (age, country_name, name) values (?, ?, ?) Hibernate: insert into person (age, country_name, name) values (?, ?, ?) 2021-11-26 13:28:05.200 TRACE 3971 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [INTEGER] - [25] 2021-11-26 13:28:05.200 TRACE 3971 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [India] 2021-11-26 13:28:05.201 TRACE 3971 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARCHAR] - [Shrirang] 2021-11-26 13:28:05.214 DEBUG 3971 --- [ main] org.hibernate.SQL : insert into person_city_company (person_id, country_name, city_id) values (?, ?, ?) Hibernate: insert into person_city_company (person_id, country_name, city_id) values (?, ?, ?) 2021-11-26 13:28:05.215 TRACE 3971 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [16] 2021-11-26 13:28:05.215 TRACE 3971 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [India] 2021-11-26 13:28:05.215 TRACE 3971 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [BIGINT] - [1] 2021-11-26 13:28:05.215 TRACE 3971 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [VARCHAR] - [India] 2021-11-26 13:28:05.218 INFO 3971 --- [ main] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements 2021-11-26 13:28:05.219 WARN 3971 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: S1009 2021-11-26 13:28:05.219 ERROR 3971 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Parameter index out of range (4 gt; number of parameters, which is 3). 2021-11-26 13:28:05.226 INFO 3971 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2021-11-26 13:28:05.247 ERROR 3971 --- [ main] o.s.boot.SpringApplication : Application run failed java.lang.IllegalStateException: Failed to execute CommandLineRunner at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:770) ~[spring-boot-2.6.0.jar:2.6.0] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:751) ~[spring-boot-2.6.0.jar:2.6.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:309) ~[spring-boot-2.6.0.jar:2.6.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.0.jar:2.6.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290) ~[spring-boot-2.6.0.jar:2.6.0] at com.shree.testjpa.TestJpaApplication.main(TestJpaApplication.java:15) ~[classes/:na] Caused by: org.springframework.orm.jpa.JpaSystemException: could not insert collection: [com.shree.testjpa.entity.Person.stayed#16]; nested exception is org.hibernate.exception.GenericJDBCException: could not insert collection: [com.shree.testjpa.entity.Person.stayed#16] at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:331) ~[spring-orm-5.3.13.jar:5.3.13] at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233) ~[spring-orm-5.3.13.jar:5.3.13] at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:566) ~[spring-orm-5.3.13.jar:5.3.13] at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) ~[spring-tx-5.3.13.jar:5.3.13] at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.3.13.jar:5.3.13] at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654) ~[spring-tx-5.3.13.jar:5.3.13] at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407) ~[spring-tx-5.3.13.jar:5.3.13] at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.13.jar:5.3.13] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.13.jar:5.3.13] at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.13.jar:5.3.13] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.13.jar:5.3.13] at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) ~[spring-data-jpa-2.6.0.jar:2.6.0] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.13.jar:5.3.13] at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.13.jar:5.3.13] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.13.jar:5.3.13] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.13.jar:5.3.13] at com.sun.proxy.$Proxy90.saveAll(Unknown Source) ~[na:na] at com.shree.testjpa.TestService.initTables(TestService.java:49) ~[classes/:na] at com.shree.testjpa.TestJpaApplication.run(TestJpaApplication.java:21) ~[classes/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:767) ~[spring-boot-2.6.0.jar:2.6.0] ... 5 common frames omitted Caused by: org.hibernate.exception.GenericJDBCException: could not insert collection: [com.shree.testjpa.entity.Person.stayed#16] at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1392) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:50) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:na] at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:344) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1416) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:507) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3299) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2434) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:449) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) ~[spring-orm-5.3.13.jar:5.3.13] ... 22 common frames omitted Caused by: java.sql.SQLException: Parameter index out of range (4 gt; number of parameters, which is 3). at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.27.jar:8.0.27] at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.27.jar:8.0.27] at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) ~[mysql-connector-java-8.0.27.jar:8.0.27] at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) ~[mysql-connector-java-8.0.27.jar:8.0.27] at com.mysql.cj.jdbc.ClientPreparedStatement.checkBounds(ClientPreparedStatement.java:1396) ~[mysql-connector-java-8.0.27.jar:8.0.27] at com.mysql.cj.jdbc.ClientPreparedStatement.getCoreParameterIndex(ClientPreparedStatement.java:1409) ~[mysql-connector-java-8.0.27.jar:8.0.27] at com.mysql.cj.jdbc.ClientPreparedStatement.setString(ClientPreparedStatement.java:1776) ~[mysql-connector-java-8.0.27.jar:8.0.27] at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.setString(HikariProxyPreparedStatement.java) ~[HikariCP-4.0.3.jar:na] at org.hibernate.type.descriptor.sql.VarcharTypeDescriptor$1.doBind(VarcharTypeDescriptor.java:46) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:73) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:276) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:271) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.type.ComponentType.nullSafeSet(ComponentType.java:365) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.type.EntityType.nullSafeSet(EntityType.java:280) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:930) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1352) ~[hibernate-core-5.6.1.Final.jar:5.6.1.Final] ... 40 common frames omitted 2021-11-26 13:28:05.249 INFO 3971 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default' 2021-11-26 13:28:05.251 INFO 3971 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2021-11-26 13:28:05.263 INFO 3971 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Я подозреваю, что проблема связана с отображением (списком) У меня есть Личная сущность.
Примечание — вызов findAll() в репозитории Person работает отлично
Комментарии:
1. пожалуйста, размещайте только соответствующий код/информацию. Что в этом такого сложного: индекс параметра вне диапазона (4 gt; количество параметров, которое равно 3)? вы передаете больше параметров, чем это возможно, или неправильно используете индексы
2.
@GeneratedValue(strategy = GenerationType.IDENTITY)
это действительно выглядит так, как будто вы передаетеid
в свои конструкторы. Постарайся этого не делать.3. Вы также можете попробовать не иметь
AUTO_INCREMENT
в своем определении таблицы. В этом случае, однако, вам придется контролировать уникальную последовательностьid
столбцов вPerson
таблице.4. @Stultuske Я не передаю больше параметров. Запросы и подготовленные заявления генерируются Spring framework
5. @ElliottFrisch Я передаю идентификатор как 0, чтобы код/бд генерировал соответствующий идентификатор.
Ответ №1:
Я думаю, проблема в том, что вы пытаетесь добавить первичный ключ к сущности, обратите внимание, что, поскольку вы используете идентификатор, spring сделает это за вас