1.在applicationContext.xml中添加mybatis配置
然后建立UserDao.xml
1、applicationContext.xml配置了service包下面的类中create开头的方法都添加了事务机制,运行–结果数据库无数据添加
2、注释掉xml中的create*的配置,看下结果,插入一条数据
3、在service的create方法或者serviceImpl类上加上注解,如下,再运行,发现无数据添加成功
下面就是建类了
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zq.model.User;
import com.zq.service.UserService;
@RequestMapping("/user")
@Controller
public class UserController {
@Autowired
private UserService userService;
@ResponseBody
@RequestMapping("/create.do")
public boolean create(User user){
try{
userService.create(user);
}catch(Exception e){
System.out.println(e.getMessage());
return false;
}
return true;
}
@ResponseBody
@RequestMapping("/list.do")
public List<User> list(User user){
return userService.list(user);
}
@RequestMapping("/toLogin.do")
public String toLogin(){
return "login";
}
}
还有UserDao.xml的SQL语句:
<where><!-- 这种写法会自动去掉第一个and -->
<if test="username!=null and username!=''">
and username = #{username}
</if>
<if test="pwd!=null and pwd!=''">
and pwd = #{pwd}
</if>
<!-- id与字符窜判断区别 -->
<if test="id !=null">
and id = #{id}
</if>
<if test="realname!=null and realname!=''">
and realname like concat('%',#{realname},'%')<!-- '%'#{realname}'%' -->
</if>
</where>
</sql>
<!-- 查询列表 -->
<select id="list" parameterType="user" resultType="user">
select * from user
<include refid="sqlWhere" />
</select>
<!-- id不需要,自增 -->
<insert id="create" parameterType="user">
insert into user(username,pwd,realname)
values(#{username},#{pwd},#{realname})
</insert>
update user username = #{username} pwd = #{pwd} realname = #{realname} where id = #{id} delete from user where id = #{id} 连接数据库后,在网页测试效果。