目录
这部分搭建环境在搭建MyBatis环境已经说过,下面是更详细的界面操作
用Maven新建一个project来测试
生成器这里选择Maven,然后名称可以自己命名,Archetype这里可以使用默认的也可以自己添加,这里使用自己添加的
新建后的界面:
然后添加相关目录:
全选这四个都新建。
新建数据库和添加数据:
CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`name`,`pwd`) values (1,'愷龍','123456'),(2,'张三','abcdef'),(3,'李四','147258369');
在pom.xml文件中添加依赖:
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
在src\main\resources下新建MyBatis核心配置文件(mybatis-config.xml):
用的引入property文件的方式
<?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="jdbc.properties"></properties>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="logImpl" value="LOG4J"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
<!-- <mapper resource="com/kailong/mapper/UserMapper.xml"/>-->
<mapper class="com.kailong.mapper.UserMapper"></mapper>
</mappers>
</configuration>
jdbc.properties:
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.user=root
jdbc.password=123456
新建如图的三个软件包,分别存放mapper接口、bean、工具类
package com.kailong.utils;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取SqlSession连接
public static SqlSession getSession(){
return getSession(true);
}
public static SqlSession getSession(boolean flag){
return sqlSessionFactory.openSession(flag);
}
}
package com.kailong.pojo;
public class User {
private int id; //id
private String name; //姓名
private String pwd; //密码
//还有其所需的构造函数,有参,无参
//set/get
//toString()
}
package com.kailong.mapper;
import com.kailong.pojo.User;
public interface UserMapper {
/**
* 查询全部用户
* @return
*/
List<User> selectUser();
}
如图:
<?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.kailong.mapper.UserMapper">
<select id="selectUser" resultType="com.kailong.pojo.User">
select * from user
</select>
</mapper>
src\test\java
下新建测试类,最好也分包一下)MyTest .java
public class MyTest {
@Test
public void selectUser() {
SqlSession session = MybatisUtils.getSession();
//方法一:
//List<User> users = session.selectList("com.kailong.mapper.UserMapper.selectUser");
//方法二:
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.selectUser();
for (User user: users){
System.out.println(user);
}
session.close();
}
}
运行结果:
public interface UserMapper {
//查询全部用户
List<User> selectUser();
//根据id查询用户
User selectUserById(int id);
}
<select id="selectUserById" resultType="com.kuang.pojo.User">
select * from user where id = #{id}
</select>
@Test
public void tsetSelectUserById() {
SqlSession session = MybatisUtils.getSession(); //获取SqlSession连接
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);//查找编号为1的用户
System.out.println(user);
session.close();
}
测试结果:
方法一:直接在方法中传递参数
1、在接口方法的参数前加 @Param属性
2、Sql语句编写的时候,直接取@Param中设置的值即可,不需要单独设置参数类型
mapper接口中添加方法:
//通过密码和名字查询用户
User selectUserByNP(@Param("username") String username,@Param("pwd") String pwd);
mapper配置文件中添加:
<select id="selectUserByNP" resultType="com.kailong.pojo.User">
select * from user where name = #{username} and pwd = #{pwd}
</select>
测试类:
@Test
public void testSelectUserByNP(){
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectUserByNP("愷龍","123456");
System.out.println(user);
session.close();
}
测试结果:
方法二:使用万能的Map
User selectUserByNP2(Map<String,Object> map);
<select id="selectUserByNP2" parameterType="map" resultType="com.kailong.pojo.User">
select * from user where name = #{username} and pwd = #{pwd}
</select>
Map<String, Object> map = new HashMap<String, Object>();
map.put("username","愷龍");
map.put("pwd","123456");
User user = mapper.selectUserByNP2(map);
如果参数过多,我们可以考虑直接使用Map实现,如果参数比较少,直接传递参数即可
/**
* 添加一个用户
* @param user
* @return
*/
int addUser(User user);
<insert id="addUser" parameterType="com.kailong.pojo.User">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
@Test
public void testAddUser() {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User(4,"愚生浅末","123456");
int i = mapper.addUser(user);
System.out.println(i);
session.commit(); //提交事务,重点!不写的话不会提交到数据库
session.close();
}
运行结果:
数据库结果:
注意:增、删、改操作需要提交事务!
一般使用update标签进行更新操作,它的配置和select标签差不多!
/**
* 修改一个用户
* @param user
* @return
*/
int updateUser(User user);
<update id="updateUser" parameterType="com.kailong.pojo.User">
update user set name=#{name},pwd=#{pwd} where id = #{id}
</update>
@Test
public void testUpdateUser() {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);
user.setPwd("yvshengqianmo");
int i = mapper.updateUser(user);
System.out.println(i);
session.commit(); //提交事务,重点!不写的话不会提交到数据库
session.close();
}
测试结果:
数据库结果:
一般使用delete标签进行删除操作,它的配置和select标签差不多
/**
* 根据ID删除用户
* @param id
* @return
*/
int deleteUser(int id);
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete>
@Test
public void testDeleteUser() {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.deleteUser(4);
System.out.println(i);
session.commit(); //提交事务,重点!不写的话不会提交到数据库
session.close();
}
测试结果:
数据库结果:
模糊查询like语句该怎么写?
第1种:在Java代码中添加sql通配符。
string wildcardname = “%smi%”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
select * from foo where bar like #{value}
</select>
第2种:在sql语句中拼接通配符,会引起sql注入
string wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
select * from foo where bar like "%"#{value}"%"
</select>