package com.mybatis.inteface;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.mybatis.pojo.User;
public interface UserInterface {
//根據表名查詢用戶信息(直接使用註解指定傳入參數名稱)
//There is no getter for property named 'tableName' in 'class java.lang.String'
//public List<User> queryUserByTableName(String tableName);
public List<User> queryUserByTableName(@Param("tableName") String tableName);
//使用註解指定傳入參數名稱
//public User login(String userName, String password);
public User login(@Param("userName") String userName, @Param("password") String password);
public User queryUserById(Integer id);
public List<User> queryUserByIds(List<Integer> ids);
public List<User> queryUserAll();
public void insertUser(User user);
public void insertUserList(List<User> users);
public void updateUser(User user);
public void updateUserList(List<User> users);
public void deleteUserById(Integer id);
}
<?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:命名空間,隨便寫,一般保證命名空間唯一 ,爲了使用接口動態代理,這裏必須是接口的全路徑名-->
<mapper namespace="com.mybatis.inteface.UserInterface">
<!--
1.#{},預編譯的方式preparedstatement,使用佔位符替換,防止sql注入,一個參數的時候,任意參數名可以接收
2.${},普通的Statement,字符串直接拼接,不可以防止sql注入,一個參數的時候,必須使用${value}接收參數
-->
<select id="queryUserByTableName" resultType="com.mybatis.pojo.User">
<!--select * from ${tableName} fail-->
<!--select * from #{tableName} fail-->
<!--select * from #{param1} fail-->
<!--select * from ${param1} success-->
select t.id as id,t.user_name as userName,t.password as password,
t.name as name,t.age as age, t.birthday as birthday,t.sex as sex,
t.created as created,t.updated as updated
from ${tableName} t
</select>
<select id="login" resultType="com.mybatis.pojo.User">
<!--select * from tb_user where user_name = #{userName} and password = #{password} fail-->
<!--select * from tb_user where user_name = #{0} and password = #{1} success-->
<!-- select * from tb_user where user_name = #{param1} and password = #{param2} success-->
select t.id as id,t.user_name as userName,t.password as password,
t.name as name,t.age as age, t.birthday as birthday,t.sex as sex,
t.created as created,t.updated as updated
from tb_user t where t.user_name = #{userName} and t.password = #{password}
</select>
<!-- statement,內容:sql語句。
id:唯一標識,在同一個命名空間下保持唯一,使用動態代理之後要求和方法名保持一致
resultType:sql語句查詢結果集的封裝類型,使用動態代理之後和方法的返回類型一致;resultMap:二選一
parameterType:參數的類型,使用動態代理之後和方法的參數類型一致
-->
<select id="queryUserById" resultType="com.mybatis.pojo.User" parameterType="int">
select t.id as id,t.user_name as userName,t.password as password,
t.name as name,t.age as age, t.birthday as birthday,t.sex as sex,
t.created as created,t.updated as updated
from tb_user t where t.id = #{id}
</select>
<select id="queryUserByIds" resultType="com.mybatis.pojo.User" parameterType="java.util.List">
select t.id as id,t.user_name as userName,t.password as password,
t.name as name,t.age as age, t.birthday as birthday,t.sex as sex,
t.created as created,t.updated as updated
from tb_user t where t.id in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
<select id="queryUserAll" resultType="com.mybatis.pojo.User">
select t.id as id,t.user_name as userName,t.password as password,
t.name as name,t.age as age, t.birthday as birthday,t.sex as sex,
t.created as created,t.updated as updated
from tb_user t
</select>
<!-- 新增的Statement
id:唯一標識,在同一個命名空間下保持唯一,使用動態代理之後要求和方法名保持一致
parameterType:參數的類型,使用動態代理之後和方法的參數類型一致
useGeneratedKeys:開啓主鍵回寫
keyColumn:指定數據庫的主鍵
keyProperty:主鍵對應的pojo屬性名
-->
<insert id="insertUser" useGeneratedKeys="true" keyColumn="id" keyProperty="id"
parameterType="com.mybatis.pojo.User">
insert into tb_user
(id,user_name,password,name,age,sex,birthday,created,updated)
values
(#{id},#{userName},#{password},#{name},#{age},#{sex},#{birthday},sysdate,sysdate)
</insert>
<insert id="insertUserList" parameterType="java.util.List">
insert into tb_user
(id,user_name,password,name,age,sex,birthday,created,updated)
select id,user_name,password,name,age,sex,birthday,created,updated
from (
<foreach collection="list" item="item" index="index" separator="UNION ALL">
select #{item.id} as id,#{item.userName} as user_name,#{item.password} as password,
#{item.name} as name,#{item.age} as age,#{item.sex} as sex,
#{item.birthday} as birthday,sysdate as created,sysdate as updated
from dual
</foreach>
) A
</insert>
<update id="updateUser" parameterType="com.mybatis.pojo.User">
update tb_user
<trim prefix="set" suffixOverrides=",">
<if test="userName!=null">user_name = #{userName},</if>
<if test="password!=null">password = #{password},</if>
<if test="name!=null">name = #{name},</if>
<if test="age!=null">age = #{age},</if>
<if test="sex!=null">sex = #{sex},</if>
<if test="birthday!=null">birthday = #{birthday},</if>
updated = sysdate,
</trim>
where id = #{id}
</update>
<update id="updateUserList" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="begin" close=";end;" separator=";">
update tb_user
<set>
<if test="item.userName!=null">user_name = #{item.userName},</if>
<if test="item.password!=null">password = #{item.password},</if>
<if test="item.name!=null">name = #{item.name},</if>
<if test="item.age!=null">age = #{item.age},</if>
<if test="item.sex!=null">sex = #{item.sex},</if>
<if test="item.birthday!=null">birthday = #{item.birthday},</if>
updated = sysdate,
</set>
where id = #{item.id}
</foreach>
</update>
<delete id="deleteUserById" parameterType="java.lang.Integer">
delete from tb_user where id=#{id}
</delete>
</mapper>
package com.mybatis.pojo;
import java.util.Date;
public class User {
private Integer id;
private String userName;//數據庫字段名user_name
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
private String created;
private String updated;
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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getUpdated() {
return updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password="
+ password + ", name=" + name + ", age=" + age + ", sex=" + sex
+ ", birthday=" + birthday + ", created=" + created
+ ", updated=" + updated + "]";
}
}
package com.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.mybatis.inteface.UserInterface;
import com.mybatis.pojo.User;
public class UserDaoTest {
public UserInterface userInterface;
@Before
public void setUp(){
try {
// 指定配置文件
String resource = "mybatis-config.xml";
// 讀取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
// 構建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 獲取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 1. 映射文件的命名空間(namespace)必須是mapper接口的全路徑
// 2. 映射文件的statement的id必須和mapper接口的方法名保持一致
// 3. Statement的resultType必須和mapper接口方法的返回類型一致
// 4. statement的parameterType必須和mapper接口方法的參數類型一致(不一定)
this.userInterface = sqlSession.getMapper(UserInterface.class);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testQueryUserByTableName() {
List<User> userList = this.userInterface.queryUserByTableName("tb_user");
for (User user : userList) {
System.out.println(user);
}
}
@Test
public void testLogin() {
System.out.println(this.userInterface.login("jingjing", "123456"));
}
@Test
public void testQueryUserById() {
System.out.println(this.userInterface.queryUserById(2));
}
@Test
public void testQueryUserByIds() {
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
List<User> userList = this.userInterface.queryUserByIds(ids);
for (User user : userList) {
System.out.println(user);
}
}
@Test
public void testQueryUserAll() {
List<User> userList = this.userInterface.queryUserAll();
for (User user : userList) {
System.out.println(user);
}
}
@Test
public void testInsertUser() {
User user = new User();
user.setId(3);
user.setAge(20);
user.setBirthday(new Date());
user.setName("大神");
user.setPassword("123456");
user.setSex(2);
user.setUserName("bigGod222");
this.userInterface.insertUser(user);
System.out.println(user.getId());
}
@Test
public void testInsertUserList() {
User user10 = new User();
user10.setId(10);
user10.setAge(20);
user10.setBirthday(new Date());
user10.setName("大神");
user10.setPassword("123456");
user10.setSex(2);
user10.setUserName("bigGod111");
User user20 = new User();
user20.setId(20);
user20.setAge(40);
user20.setBirthday(new Date());
user20.setName("大力神");
user20.setPassword("123456");
user20.setSex(2);
user20.setUserName("bigGod222");
List<User> users = new ArrayList<User>();
users.add(user10);
users.add(user20);
this.userInterface.insertUserList(users);
}
@Test
public void testUpdateUser() {
User user = new User();
user.setId(1);
user.setBirthday(new Date());
user.setName("靜靜");
user.setPassword("123456");
user.setSex(0);
user.setUserName("Jinjin");
this.userInterface.updateUser(user);
}
@Test
public void testupdateUserList() {
User user1 = new User();
user1.setId(1);
user1.setName("name11");
user1.setUserName("username11");
User user2 = new User();
user2.setId(2);
user2.setName("name22");
user2.setUserName("username22");
List<User> users = new ArrayList<User>();
users.add(user1);
users.add(user2);
this.userInterface.updateUserList(users);
}
@Test
public void testDeleteUserById() {
this.userInterface.deleteUserById(1);
}
}
log4j.rootLogger=DEBUG,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%l] [%p]:%m%n
<?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">
<!-- 根標籤 -->
<configuration>
<properties>
<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
<property name="username" value="system"/>
<property name="password" value="bruce123"/>
</properties>
<!-- 環境,可以配置多個,default:指定採用哪個環境 -->
<environments default="development">
<!-- id:唯一標識 -->
<environment id="test">
<!-- 事務管理器,JDBC類型的事務管理器 -->
<transactionManager type="JDBC" />
<!-- 數據源,池類型的數據源 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis-110" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
<environment id="development">
<!-- 事務管理器,JDBC類型的事務管理器 -->
<transactionManager type="JDBC" />
<!-- 數據源,池類型的數據源 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}" /> <!-- 配置了properties,所以可以直接引用 -->
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/mapper/UserMapper.xml" />
</mappers>
</configuration>