Mybatis使用接口实现添加一直加不进去
这是单元测试的部分:
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
public void test03() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapperAnnotation mapper = openSession.getMapper(EmployeeMapperAnnotation.class);
Employee employee=new Employee(null, "leihong", "159159");
//System.out.println(employee);
mapper.insertuser(employee);
openSession.commit();
System.out.println("成功");
}finally{
openSession.close();
}
}
这是接口的内容:
package com.atguigu.mybatis.dao;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import com.atguigu.mybatis.bean.Employee;
public interface EmployeeMapperAnnotation {
@Select("select * from user where id=#{id}")
@Insert("insert into user(username,password) values(#{username},#{password})")
public Employee getEmpById(Integer id);
public Employee insertuser(Employee employee);
}
这是sql映射xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperAnnotation">
<select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee">
select * from user where id = #{id}
</select>
<insert id="insertuser">
insert into user(username,password) values(#{username},#{password})
</insert>
</mapper>
[b]这是封装的类:[/b]
package com.atguigu.mybatis.bean;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String username;
private String password;
public Employee() {
super();
// TODO Auto-generated constructor stub
}
public Employee(Integer id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Employee [id=" + id + ", username=" + username + ", password=" + password + "]";
}
这是全局配置文件:
<mappers>
<package name="com.atguigu.mybatis.dao"/>
</mappers>