######将数据添加到数据库中发生错误
数据库如下:
相应代码如下:
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/property_manage"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="property.manage.mapper.PropertyMapper"/>
</mappers>
</configuration>
接口PropertyMapper.java
package property.manage.mapper;
import org.apache.ibatis.annotations.Insert;
import property.manage.entity.Household;
public interface PropertyMapper {
@Insert("insert into household(name,sex,grade) values(#{name},#{sex},#{grade})")
int addHousehold(Household household);
}
Household.java
package property.manage.entity;
import lombok.Data;
@Data
public class Household {
String hid;
final String name;
final String sex;
final int grade;
}
Main.java
package property.manage;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import property.manage.entity.Household;
import property.manage.mapper.PropertyMapper;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
try(SqlSession sqlSession = factory.openSession(true)){
PropertyMapper mapper = sqlSession.getMapper(PropertyMapper.class);
System.out.println(mapper.addHousehold(new Household("小敏","M",1)));
}
}
}
运行Main.java时报错:
不改变数据库结构,将(123456789,小敏,M,1)添加到数据库中
求详细代码解决方案