博客主页:作者主页
简介:JAVA领域优质创作者、一名在校大三学生、在校期间参加各种省赛、国赛,斩获一系列荣誉
关注我:关注我学习资料、文档下载统统都有,每日定时更新文章,励志做一名JAVA资深程序猿
思路流程:搭建环境–>导入Mybatis—>编写代码—>测试
1.搭建实验数据库
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,'hhh','123456'),(2,'张
三','abcdef'),(3,'李四','987654');
2.导入MyBatis相关 jar 包
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.49version>
dependency>
mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<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://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/sxau/dao/UserMapper.xml"/>
mappers>
configuration>
MybatisUtils.java
package com.sxau.utils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
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();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
package com.sxau.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
package com.sxau.dao;
import com.sxau.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
List<User> getUserList();
}
namespace 十分重要,不能写错!
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sxau.dao.UserMapper">
<select id="getUserList" resultType="com.sxau.pojo.User">
select * from mybatis.user
select>
mapper>
public class MyTest {
@Test
public void test(){
//第一步: 获得sqlSession
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:执行SQL语句 getmapper
// UserDao mapper = sqlSession.getMapper(UserDao.class);
// List userList = mapper.getUserList();
//方式二:
List<User> userList = sqlSession.selectList("com.sxau.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
可能出现问题说明:Maven静态资源过滤问题
在pom.xml中加入以下代码块
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
结论
配置文件中namespace中的名称为对应Mapper接口或者Dao接口的完整包名,必须一致!
需求:根据id查询用户
package com.sxau.dao;
import com.sxau.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
//查询全部用户
List<User> getUserList();
//根据id查询用户
User getUserById(int id);
}
<select id="getUserById" parameterType="int" resultType="com.sxau.pojo.User">
select * from mybatis.user where id = #{id}
select>
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
小练习:根据 密码
和 用户名
查询用户信息
思路一:直接在方法中传递参数
//通过密码和名字查询用户
User selectUserByNameAndPwd(@Param("username") String username,@Param("pwd") String pwd);
/*
*/
思路二:使用万能的Map
1. 在接口方法中,参数直接传递Map;
User selectUserByNP2(Map<String,Object> map);
<select id="selectUserByNP2" parameterType="map"
resultType="com.sxau.pojo.User">
select * from user where name = #{username} and pwd = #{pwd}
</select>
@Test
public void selectUserByNP2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("username","hhh");
map.put("pwd","123456");
User user = mapper.selectUserByNP2(map);
//提交事务
sqlSession.commit();
sqlSession.close();
}
如果参数过多,我们可以考虑直接使用Map来实现参数传递,如果参数比较少,直接传递参数即可
我们一般使用insert标签进行插入操作,它的配置和select标签差不多!
需求:给数据库增加一个用户
//添加用户
int addUser(User user);
<insert id="addUser" parameterType="com.sxau.pojo.User">
insert into mybatis.user(id, name, pwd) VALUES (#{id},#{name},#{pwd});
insert>
3.在测试类中进行测试
//增删改 需要提交事务
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(4,"hahah","123123"));
//提交事务
sqlSession.commit();
sqlSession.close();
}
注意点:增、删、改操作需要提交事务!
我们一般使用update标签进行更新操作,它的配置和select标签差不多!
需求:修改用户的信息
//修改用户
int updateUser(User user);
<update id="updateUser" parameterType="com.sxau.pojo.User">
update mybatis.user
set name=#{name},pwd=#{pwd}
where id=#{id};
update>
3.在测试类中进行测试
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(4,"qqq","123123"));
sqlSession.commit();
sqlSession.close();
}
我们一般使用delete标签进行删除操作,它的配置和select标签差不多!
需求:根据id删除一个用户
根据id删除用户
int deleteUser(int id);
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
delete>
3.在测试类中进行测试
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();
}
小结
在MyBatis中模糊查询like语句该怎么写?
第1种:在Java代码中添加sql通配符。
//like模糊查询
List<User> getUserLike(String value);
<select id="getUserLike" resultType="com.sxau.pojo.User">
select * from mybatis.user where name like #{value}
</select>
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userLike = mapper.getUserLike("%李%");
for (User user : userLike) {
System.out.println(user);
}
}
第2种:在sql语句中拼接通配符,会引起sql注入
//like模糊查询
List<User> getUserLike(String value);
<select id=”getUserLike”>
select * from foo where bar like "%"#{value}"%"
</select>
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userLike = mapper.getUserLike("李");
for (User user : userLike) {
System.out.println(user);
}
}