参数索引超出范围(4 > 参数个数,即 3)
Posted
技术标签:
【中文标题】参数索引超出范围(4 > 参数个数,即 3)【英文标题】:Parameter index out of range (4 > number of parameters, which is 3) 【发布时间】:2022-01-04 07:19:44 【问题描述】:我收到“参数索引超出范围(4 > 参数数量,即 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 List<City> stayed;
==
package com.shree.testjpa.repo;
import com.shree.testjpa.entity.City;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CityRepository extends JpaRepository<City, Long>
==
package com.shree.testjpa.repo;
import com.shree.testjpa.entity.Company;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CompanyRepository extends JpaRepository<Company, Long>
==
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 JpaRepository<Person, Long>
==
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()
//List<City> cityList = new ArrayList<>();
//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"));
List<City> cityList = cityRepository.findAll();
List<Person> people = new ArrayList<>();
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();
== 应用程序.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
==
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.shree.testjpa</groupId>
<artifactId>test-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test-jpa</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
== 带有示例数据的 MySql SQL: =======
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;
== ER图
== 例外:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: 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 > 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 > 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.
我怀疑问题出在我在 Person 实体中的映射(列表)。
注意-对 Person 存储库的 findAll() 调用工作正常
【问题讨论】:
请只发布相关代码/信息。这有什么难的:参数索引超出范围(4>参数数量,即3)?您正在传递更多参数,或者使用错误的索引@GeneratedValue(strategy = GenerationType.IDENTITY)
看起来您将id
传递给您的构造函数。尽量不要那样做。
您也可以尝试在表定义中不包含AUTO_INCREMENT
。但是,在这种情况下,您必须控制 id
表中 id
列的唯一顺序。
@Stultuske 我没有传递更多参数。查询和预处理语句由 Spring 框架生成
@ElliottFrisch 我将 id 作为 0 传递,以便 code/db 生成适当的 id。
【参考方案1】:
我认为问题在于您正在尝试将主键添加到实体上,请注意,由于您使用 IDENTITY,spring 会为您执行此操作
【讨论】:
以上是关于参数索引超出范围(4 > 参数个数,即 3)的主要内容,如果未能解决你的问题,请参考以下文章
java.sql.SQLException:参数索引超出范围(2 > 参数个数,即 0)
java.sql.SQLException:spring boot中的参数索引超出范围(6>参数个数,即5)