学习内容:对user表进行增删改查
项目结构:
IUserDao
package wo.dao;
import wo.domain.QueryVo;
import wo.domain.User;
import java.util.List;
//用户得持久层接口
public interface IUserDao {
//查询所有用户
List<User> findAll();
//保存方法
void saveUser(User user);
//更新用户
void updateUser(User user);
//根据id删除用户
void deleteUser(Integer userId);
//根据id查询用户信息
User findById(Integer userId);
//根据名称模糊查询用户信息
List<User> findByName(String username);
//查询总用户数
int findTotal();
//根据queryVo中的条件查询用户
List<User> findUserByVo(QueryVo vo);
}
QueryVo
package wo.domain;
public class QueryVo {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
IUSerDao.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="wo.dao.IUserDao">
<!--配置查询所有-->
<select id="findAll" resultType="wo.domain.User">
select * from user
</select>
<!--保存用户-->
<insert id="saveUser" parameterType="wo.domain.User">
<!--配置插入操作后,获取插入数据的id-->
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
SELECT last_insert_id();
</selectKey>
insert into user(username,address,sex,birthday)VALUE (#{username},#{address},#{sex},#{birthday});
</insert>
<!--更新用户-->
<update id="updateUser" parameterType="wo.domain.User">
UPDATE USER SET username=#{username},address=#{address},sex=#{sex},birthday=#{birthday}where id=#{id};
</update>
<!--删除用户-->
<delete id="deleteUser" parameterType="int">
DELETE FROM USER WHERE id=#{id};
</delete>
<!--根据id查询用户-->
<select id="findById" parameterType="int" resultType="wo.domain.User">
SELECT * from user where id=#{id};
</select>
<!--根据名称模糊查询用户信息-->
<select id="findByName" parameterType="string" resultType="wo.domain.User" >
SELECT * from user WHERE username LIKE #{name};
</select>
<!--获取用户的总记录条数-->
<select id="findTotal" resultType="int">
SELECT COUNT(id) FROM user;
</select>
<!--根据queryVo查询用户信息-->
<select id="findUserByVo" parameterType="wo.domain.QueryVo" resultType="wo.domain.User" >
SELECT * from user WHERE username LIKE #{user.username};
</select>
</mapper>
SqlMapConfig.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">
<!--mybatis的主配置文件-->
<configuration>
<!--配置环境 -->
<environments default="mysql">
<!--配置mysql环境-->
<environment id="mysql">
<!--配置事务的类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源(连接池)-->
<dataSource type="POOLED">
<!--配置连接数据库的4个基本信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssmtest?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--指定映射配置文件的内容,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
<mapper resource="wo/dao/IUserDao.xml"/>
</mappers>
</configuration>
来自黑马java