One, Mybatis
1. What is the difference between #{} and ${}?
2. What should I do when the attribute name in the entity class is different from the field name in the table?
2. The first Mybatis project
1. Build the environment
- Create database and table
CREATE DATABASE mybatis1;
USE mybatis1;
CREATE TABLE users(
uid INT PRIMARY KEY,
uname VARCHAR(32),
uaccount VARCHAR(32),
upwd VARCHAR(32)
)
- Import dependencies
<!--导入依赖-->
<dependencies>
<!--msql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
</dependencies>
- Create entity class
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Users implements Serializable {
private long uid;
private String uname;
private String uaccount;
private String upwd;
}
- Create mybatis-config.xml file
<?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 resource="db.properties"/>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<package name="com.codewen.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/codewen/mapper/UsersMapper.xml"/>
</mappers>
</configuration>
- Create a tool class to get SQLSession
public class SqlSessionUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
String resource = "mybatis-config.xml";
try {
InputStream is = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
- Create mapper
public interface UsersMapper {
List<Users> queryAllUsers();
}
- Create the xml corresponding to the mapper
<?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.codewen.mapper.UsersMapper">
<select id="UsersMapper" resultType="com.codewen.entity.Users">
SELECT * FROM users
</select>
</mapper>
- Create test class
public class Test01 {
public static void main(String[] args) {
SqlSession session = SqlSessionUtil.getSession();
UsersMapper mapper = session.getMapper(UsersMapper.class);
List<Users> users = mapper.queryAllUsers();
for(Users user : users) {
System.out.println(user);
}
}
}
Register mapper (there are three kinds of resource, class, url)
<mappers>
<mapper resource="com/codewen/mapper/UsersMapper.xml"/>
<!--<mapper class="com.codewen.mapper.UsersMapper"/>-->
</mappers>
The attribute name and the field name do not match
The first type: modify the sql statement, alias the field name in the sql column as the attribute name.
The second type: use the resultMap, only need to map different
Three, Mybatis basic CURD
select statement review
select, query statement
<mapper namespace="zsj.dao.UserDao">
<select id="getUserList" resultType="zsj.pojo.User">
select * from user
</select>
</mapper>
- id: is the method name in the corresponding interface class
- resultType: The return value of the Sql statement execution!
- paramaterType: the type of parameters passed by the function
Example of using paramaterType (query a user)
UserDao add statement:
// 根据id查询用户
User getUserById(int id);
UserDao.xml add statement:
<!--根据id查询用户-->
<select id="getUserById" resultType="zsj.pojo.User" parameterType="zsj.pojo.User">
select * from user where id = #{
id}
</select>
Test program add statement:
//根据id查询用户
User user = userDao.getUserById(2);
System.out.println(user);
insert
1. Add the corresponding method in UserDao
// 插入一个用户
int addUser(User user);
2. Add the corresponding statement in UserDao.xml
<insert id="addUser" parameterType="zsj.pojo.User">
insert into user(id,uname,pwd)values(#{
id},#{
uname},#{
pwd})
</insert>
3. Test
@Test
public void add(){
SqlSession session = MybatisUtils.getSession();
UserDao userDao = session.getMapper(UserDao.class);
/*
* 插入一个用户
* */
User add = new User(3,"srman","18277407480");
userDao.addUser(add);
//一定要提交事务
session.commit();
List<User> users01 = userDao.getUserList();
for (User ur: users01){
System.out.println(ur.toString());
}
session.close();
}
update
1. Add the corresponding method in UserDao
// 修改一个用户
int updateUser(User user);
2. Add the corresponding statement in UserDao.xml
<update id="updateUser" parameterType="zsj.pojo.User">
update user set uname=#{
uname}, pwd=#{
pwd} where id = #{
id} ;
</update>
3. Test
@Test
public void update(){
SqlSession session = MybatisUtils.getSession();
UserDao userDao = session.getMapper(UserDao.class);
/*
* 插入一个用户
* */
User update = new User(3,"srman","19976253559");
userDao.updateUser(update);
//一定要提交事务
session.commit();
List<User> users01 = userDao.getUserList();
for (User ur: users01){
System.out.println(ur.toString());
}
session.close();
}
Four, dynamic sql and tags
1, sql tag and include tag
Use the sql tag to reuse sql, id is the name of the sql statement
<sql id="queryAllBooks">
select * from book;
</sql>
sql tag and include tag for sql reuse
<include refid="queryAllBooks"/>
2.
If tag usage is similar to if tag in java, and the test attribute is the content of judgment
<if test="btime != null">
btime=#{
btime}
</if>
<if test="author_array != null and author_array[0] != null">
and bauthor=#{
author_array[0]}
</if>
3. Where tag: The where tag is used to replace the traditional where in sql, and is generally used with the if tag.
The role of the where tag:
If there is no statement after where, then the last sql will not add where.
If there is a statement after where, then the and of the first statement will be removed
SELECT * FROM book
<where>
<if test="btime != null">
btime=#{
btime}
</if>
<if test="author_array != null and author_array[0] != null">
and bauthor=#{
author_array[0]}
</if>
</where>
4. Set tag The
set tag is used to replace the traditional set in SQL. Generally , the set tag is used in conjunction with the if tag
: in the SQL used for update, the extra comma at the end will be removed
update book
<set>
<if test="bname!=null and bname!=''">
bname=#{
bname},
</if>
<if test="bauthor!=null and bauthor!=''">
bauthor=#{
bauthor},
</if>
<if test="bintroduction!=null and bintroduction!=''">
bintroduction=#{
bintroduction}
</if>
</set>
...
5. The bind tag The
bind tag is equivalent to splicing the required characters in the value value, and then replacing the spliced parameters with the value in the name. (Generally used for splicing with #{} values)
Using bind to splice strings can not only avoid SQL modification due to database replacement, but also prevent SQL injection.
<bind name="bindfparam" value=" '%'+ parameterMap.fparam +'%' "/>
concat(bname,bauthor,bcategory) like #{
bindfparam}
6. Foreach tag: You can iterate object properties, arrays, collections, object arrays, object collections, build in conditional statements or batch operation statement
collections: indicate the properties, arrays, collections, object arrays, and object collections of the objects to be iterated
- item: the single element to be iterated in the collection
- open: Indicates what the beginning of the statement
- close: Indicates what end of the statement
- separator: Indicates the division of the sentence
- index: In list, Set, and array, index represents the position of the current iteration. In map, index refers to the key of the element, which is generally not used