MyBatis多参数传递之注解方式示例

时间:2022-12-25 23:50:05

IUserOperation.java文件:

package com.yihaomen.mybatis.inter;

import org.apache.ibatis.annotations.Param;

import com.yihaomen.mybatis.model.User;

public interface IUserOperation {
public User selectUserByID(int id);
public User selectUserByNameAge(@Param("name") String userName,@Param("age") int userAge);

}
 



把函数中的参数名称为----userName的参数绑定到sql(见本文中的user.xml:文件中的SQL)语句中的name参数中




User.java:


package com.yihaomen.mybatis.model;
public class User { private int id;    private String userName;    private String userAge;    private String userAddress;        public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getUserAge() {        return userAge;    }    public void setUserAge(String userAge) {        this.userAge = userAge;    }    public String getUserAddress() {        return userAddress;    }    public void setUserAddress(String userAddress) {        this.userAddress = userAddress;    }}



user.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="com.yihaomen.mybatis.inter.IUserOperation">
<select id="selectUserByID" parameterType="int" resultType="User">
select * from `user` where id = #{id}
</select>


<select id="selectUserByNameAge" resultType="User">
select * from `user` u where u.userName = #{name} and u.userAge=#{age}
</select>

</mapper>


Configuration.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">
<configuration>
<typeAliases>
<typeAlias alias="User" type="com.yihaomen.mybatis.model.User"/>
</typeAliases>

<environments default="development">
<environment id="development">
<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/test" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>

<mappers>
<mapper resource="com/yihaomen/mybatis/model/User.xml"/>
</mappers>
</configuration>