环境 : idea mybatis mysql jdk1.8 ; 功能 : 使用mybatis框架, 插入一个用户; 代码: @Test
public void findUserById() throws IOException {
//加载著配置文件,获取文件流
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder factory = new SqlSessionFactoryBuilder();
SqlSessionFactory build =factory.build(in);
SqlSession sqlSession =build.openSession(true);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setUsername("789");
int i =userMapper.addUser(user);
sqlSession.close();
in.close();
}
@Insert({"INSERT INTO user(username) VALUES (username=#{username});"})
int addUser(User user); 相关mybatis配置 ; 然后运行代码 ,效果如下: Idea 日志信息 DEBUG [main] - PooledDataSource forcefullyclosed/removed all connections. DEBUG [main] - PooledDataSource forcefullyclosed/removed all connections. DEBUG [main] - PooledDataSource forcefullyclosed/removed all connections. DEBUG [main] - PooledDataSource forcefullyclosed/removed all connections. DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection1686369710. DEBUG [main] - ==> Preparing: INSERT INTO user(username) VALUES(username=?); DEBUG [main] - ==> Parameters:789(String) DEBUG [main] - <== Updates: 1 DEBUG [main] - Closing JDBC Connection[com.mysql.jdbc.JDBC4Connection@6483f5ae] DEBUG [main] - Returned connection1686369710 to pool. 数据库信息: Id username sex 1 0 null 乍一看,以为是set/get属性注入问题 ,然后发现全部都给了, 后台也没看出来什么问题, 以为是数据库问题, 然后小海豚里面运行了一条sql语句, INSERT INTO user(username) VALUES ('123');发现正常插入; 解决方案: 把 idea控制台显示的sql放进入小海豚跑了一波发现是sql语句写错了; 修改sql之后 @Insert({"INSERT INTO user(username) VALUES (username);"})
int addUser(User user); 正常插入 Id username sex 1 789 null 留给大家借鉴吧, 顺便提个问题 :
那个错误的sql, 我觉得也可以插入值, username=789 这样子才对, 可是为什么会为0呢?
|