1.可以设置自动提交
在创建工具类的时候可以填入参数设置为自动提交
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
为什么写一个true就可以实现自动提交呢?
点进去看源码
这是源码接口的实现类的方法,显示可以设置为自动提交。
2.编写接口增加注解
public interface UserMapper {
@Select("select * from user")
List<User> getUserList();
//有多个参数的时候必须使用@Param注解
@Select("select * from user where id = #{id} and name = #{name}")
User getUserByid(@Param("id") int id, @Param("name") String name);
@Insert("insert into User(id,name,pwd) values(#{id},#{name},#{password})")
int addUser(User user);
}
3.编写测试类
@Test
public void test3(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(6,"yf6","122233"));
// sqlSession.commit();
sqlSession.close();
}
}