Mybatis實現增刪改查

<?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">
<!--寫sql的文件  -->
<!--命名空間,xml文件和dao接口對應  -->
<mapper namespace="com.cyw.dao.UserDao">
	<sql id="sqlWhere">
		<where><!--這種寫法會自動去掉第一個and  -->
			<if test="username!=null and username!=''">
					and username=#{username}
			</if>
			
			<if test="pwd!=null and pwd!=''">
					and pwd=#{pwd}
			</if>
			
			<if test="id!=null">
					and id=#{id}
			</if>
			
			<if test="realname!=null and realname!=''">
					and realname like concat('%',#{realname},'%')	
			</if><!--concat是用於連接字符串的函數  -->
		</where>
	</sql>
	<!--查詢列表  -->
	<select id="list" parameterType="user" resultType="user">
	<!--id要和userdao接口的方法名一致-->
		select * from 
		user where username = #{username} and pwd = #{pwd}
	</select>
	
	<!--id不需要,自增  ,所以不能整條記錄直接插入,要指名變量名-->
	<insert id="create" parameterType="user">
		insert into user(username,pwd,realname)
		values(#{username},#{pwd},#{realname})
	</insert>
	
	<!--修改  -->
	<update id ="update" parameterType="user">
		update user
		<set>
			<if test="username!=null and username!=''">
				username=#{username},
			</if>
			<if test="pwd!=null and pwd!=''">
				pwd=#{pwd},
			</if>
			<if test="realname!=null and realname!=''">
				realname = #{realname},	
			</if>
		</set>
		where id=#{id}
		<!-- set
		username = #{username},pwd=#{pwd}
		where id=#{id} -->
	</update>
	
	<delete id="delete" parameterType="integer">
		delete from user where id = #{id}
	</delete>
	
	<!--批量操作  -->
	<update id="updateBatch" parameterType="List">
		update user set pwd='123' where id in
		<foreach item="item" index="index" collection="list" open="("
			separator="," close=")">
			#{item}
		</foreach>
	</update>
</mapper>

在UserDao和UserService中寫相應的方法

UserServiceImpl中實現接口

package com.cyw.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cyw.dao.UserDao;
import com.cyw.model.User;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	//用於根據類型實例化,不用new
	private UserDao userDao;
	
	@Override
	public List<User> list(User user) {
		return userDao.list(user);
	}
	
	@Override
	public void create(User user) {
		userDao.create(user);
	}
	
	@Override
	public void update(User user) {
		userDao.update(user);
	}
	
	@Override
	public void delete(Integer id) {
		userDao.delete(id);
	}
	
	@Override
	public void updateBatch(List<Integer> list) {
		userDao.updateBatch(list);	
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章