MyBatis 入门(一)--基础方式
项目的基础配置见入门,这里只把变化点说明
一、建立接口 UserMapper.java
-
public interface UserMapper {
-
-
public List<User> getAllUser();
-
-
public User getUserById(String userId);
-
-
public int insert(User user);
-
-
public int update(User user);
-
-
public int delete(User user);
-
-
}
二 修改 UserMapper.xml
-
<?xml version="1.0" encoding="UTF-8"?>
-
<!DOCTYPE mapper
-
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
-
"">
-
<mapper namespace="com.elements.user.mapper.UserMapper">
-
注意这里与原来的方式不同 这里必须和你的接口路径+名称一直(不包括.java)
-
-
<resultMap type="com.elements.user.model.User" id="usermap">
-
<id column="userId" property="userId"/>
-
<result column="UserName" property="UserName"/>
-
<result column="UserEmail" property="UserEmail"/>
-
</resultMap>
-
-
-
<select id="getAllUser" resultMap="usermap">
-
select * from mybatis.user
-
</select>
-
-
<select id="getUserById" resultMap="usermap" parameterType="String">
-
select * from mybatis.user where userId= #{userId}
-
</select>
-
-
-
<insert id="insert" parameterType="com.elements.user.model.User">
-
insert into mybatis.user (UserName, UserEmail) values (
-
#{UserName}, #{UserEmail}
-
)
-
</insert>
-
-
<update id="update" parameterType="com.elements.user.model.User">
-
update mybatis.user set UserName=#{UserName},
-
UserEmail=#{UserEmail}
-
where userId= #{userId}
-
</update>
-
-
<delete id="delete" parameterType="String">
-
delete mybatis.user where userId= #{userId}
-
</delete>
-
-
</mapper>
三、 mybatis-config.xml配置
这里变成了接口的类
-
<?xml version="1.0" encoding="UTF-8"?>
-
<!DOCTYPE configuration
-
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
-
"">
-
-
<configuration>
-
<properties resource="jdbc.properties" />
-
<environments default="dev">
-
<environment id="dev">
-
<transactionManager type="JDBC" />
-
<dataSource type="POOLED">
-
<property name="driver" value="${driver}" />
-
<property name="url" value="${url}" />
-
<property name="username" value="${username}" />
-
<property name="password" value="${password}" />
-
</dataSource>
-
</environment>
-
</environments>
-
<mappers>
-
-
<mapper class="com.elements.user.mapper.UserMapper"/>
-
</mappers>
-
</configuration>
四、测试类
-
public class TestUser {
-
-
@Test
-
public void TestSelectAll() throws IOException {
-
String resource = "mybatis-config.xml";
-
InputStream inputStream = Resources.getResourceAsStream(resource);
-
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
-
.build(inputStream);
-
-
SqlSession session = sqlSessionFactory.openSession();
-
-
try {
-
-
UserMapper user = (UserMapper) session.getMapper(UserMapper.class);
-
List<User> userlist = user.getAllUser();
-
System.out.print(userlist);
-
-
} finally {
-
session.close();
-
}
-
-
}
-
}
项目代码下载:
阅读(3749) | 评论(0) | 转发(0) |