Table of contents
1. Pass parameters to sql statement
1. Pass parameters to sql statement
1. Basic use of MyBatis framework
The jar packages used are as follows:
<!-- 测试包-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<!-- MyBatis核心-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- 数据库连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
To use MyBatis, you need to implement an entity class corresponding to a table corresponding to a business interface corresponding to a mapper mapping.
The mapper mapping is equivalent to the implementation class of the business interface. It's just that the Java code and sql code are distinguished through the mapper.xml configuration file.
Note: Methods defined in the business interface cannot be overloaded, because when configuring through xml, the sql statement for the method configuration only looks at the method name.
as follows:
public interface EmployeeMapper {
//通过id查找员工
Employee queryById(Integer id);
//通过id name 查找员工
Employee queryById(Integer id,String name);
}
Because the same method name is used, problems will occur when xml encapsulates sql statements based on the method name.
2. Use ${ key } and #{ key } to pass parameters
Case code:
<!-- 通过#{key}传入参数 -->
<select id="queryById" resultType="com.alphamilk.pojo.Employee">
select * from mysqltest.employee where id = #{id}
</select>
<!--通过${key} 传入参数-->
<select id="queryByName" resultType="com.alphamilk.pojo.Employee">
select * from mysqltest.employee where name = ${name}
</select>
the difference:
The essence of #{key} is to perform placeholder processing and replace the value of id in the code. 【Recommended Use】
The essence of ${key} is to splice strings, which is encapsulated into a complete SQL statement in the case code.
Note: When using the value of #{key} instead, the column name and container name cannot be passed in.
3. Implement MyBatis testing function
To complete the test function, you need to implement the following steps:
1. Create the resource class is of ibatis
2. Create a SqlSessionFactoryBuilder object and perform Build( is ) to obtain the SqlSessionFactory object
3. Obtain SqlSession through the openSession method of the SqlSessionFactory object
4. Get the Mapper object
5.Perform the operation
6. Commit transactions and close related flows
Case code:
public class MybatisTest {
@Test
public void Test() throws IOException {
//步骤1,读取资源
InputStream is = Resources.getResourceAsStream("mybatisConfig.xml");
//步骤2,创建sqlSessionFactory
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//步骤3,创建SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//步骤4,获取Mapper对象
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
//执行对应操作
Employee employee = employeeMapper.queryById(1);
System.out.println(employee);
//管理事务提交与关闭操作
sqlSession.close();
}
}
2. Data input
Data entry concepts:
Data input here specifically refers to the form in which data is passed in when the upper-layer method (such as the Service method) calls the Mapper interface.
- Simple type: a data type that contains only one value
- Basic data types: int, byte, short, double,…
- Packaging types of basic data types: Integer, Character, Double,…
- String type: String
- Complex type: a data type that contains multiple values
- Entity class types: Employee, Department,…
- Collection types: List, Set, Map,…
- Array type: int[], String[],…
- Composite type: List<Employee>, entity class contains collection...
1. A single simple data type
Since there is only one simple parameter, the key in #{key} or ${key} can be filled with any value. Of course, it is recommended to use the original parameter name.
2. Entity object type
When the incoming data is an entity object type, you only need to correspond to its attributes one by one.
Case:
3. Multiple simple data types
When there are multiple parameters in a business method, please note that the key in #{key} or ${key} cannot be written randomly, and it cannot be entered directly through formal parameters. There are two solutions to the problem of inputting multiple simple data types.
3.1 Use annotation parameters to solve
Need to use @Param annotation
Case:
3.2 Use sequential method to solve
Parameters can also be matched in the order of arg0, arg1...
Case code:
4.map type
Just pass in key=map
The abstract method corresponding to the interface
int updateEmployeeByMap(Map<String, Object> paramMap);
Corresponding sql statement
<update id="updateEmployeeByMap">
update t_emp set emp_salary=#{empSalaryKey} where emp_id=#{empIdKey}
</update>
scenes to be used
There are many scattered parameters that need to be passed, but no corresponding entity class types can be used. It is too troublesome to use @Param annotations to pass them in one by one. So they are all encapsulated into Map.
3. Data output
Data output concept:
Data output generally comes in two forms:
- The number of affected rows returned by the addition, deletion and modification operations: just use the int or long type to receive it directly
- Query results of query operations
What we need to do is to specify the output data type of the query!
And in the insertion scenario, the primary key data can be displayed back!
1. A single simple type
<!--此处的namespace修改为对应的接口全类名-->
<mapper namespace="com.alphamilk.EmployeeMapper">
<!-- resultType 对应 类型的全限定符-->
<select id="querySalaryById" resultType="java.lang.Integer">
select salary from mysqltest.employee where id = #{id}
</select>
<select id="queryNameById" resultType="java.lang.String">
select name from mysqltest.employee where id=#{id}
</select>
</mapper>
Among the general simple types, Java has corresponding abbreviations. You can use String int to replace java.lang.String, etc.
2. Return entity class object
Returns the fully qualified qualifier of the class plus the class name
<!--此处的namespace修改为对应的接口全类名-->
<mapper namespace="com.alphamilk.EmployeeMapper">
<!-- resultType 对应 类型的全限定符-->
<select id="" resultType="com.alphamilk.pojo.Employee">
</select>
</mapper>
3. Return Map type
<!-- Map<String,Object> selectEmpNameAndMaxSalary(); -->
<!-- 返回工资最高的员工的姓名和他的工资 -->
<select id="selectEmpNameAndMaxSalary" resultType="map">
SELECT
emp_name 员工姓名,
emp_salary 员工工资,
(SELECT AVG(emp_salary) FROM t_emp) 部门平均工资
FROM t_emp WHERE emp_salary=(
SELECT MAX(emp_salary) FROM t_emp
)
</select>
4. Return List type
<!-- List<Employee> selectAll(); -->
<select id="selectAll" resultType="com.atguigu.mybatis.entity.Employee">
select emp_id empId,emp_name empName,emp_salary empSalary
from t_emp
</select>
5. Return the primary key value
<!-- int insertEmployee(Employee employee); -->
<!-- useGeneratedKeys属性字面意思就是“使用生成的主键” -->
<!-- keyProperty属性可以指定主键在实体类对象中对应的属性名,Mybatis会将拿到的主键值存入这个属性 -->
<insert id="insertEmployee" useGeneratedKeys="true" keyProperty="empId">
insert into t_emp(emp_name,emp_salary)
values(#{empName},#{empSalary})
</insert>
4. Alias
Since the content to be filled in when outputting the return value includes the full qualifier of the class, this operation is troublesome, so Java comes with 72 default aliases. For example, java.lang.String can be written directly as String, etc. But for general entity object types, there is no
1.xml set alias
Configure in MyBatis-config.xml
Single alias
Case code:
<typeAliases>
<!-- 单个xml配置-->
<typeAlias type="com.alphamilk.pojo.Employee" alias="Employee"/>
</typeAliases>
wrap alias
When aliasing is used in a package, the aliases of all classes under the package correspond to their class names.
<typeAliases>
<!-- 包起别名-->
<package name="com.alphamilk.pojo.Employee"/>
</typeAliases>
2. Annotate alias
If you think that configuration in xml is very troublesome and unsightly, you can use annotations to create aliases in the entity class.