Python 官方文档:入门教程 => 点击学习
目录1、mybatis第一个程序1.1、代码演示1.2、问题说明2、CRUD操作2.1、namespace2.2、select2.3、insert2.4、update2.5
思路流程:搭建环境–>导入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.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>Mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
编写MyBatis核心配置文件mybatis-config.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核心环境-->
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!-- 数据库8.0以上useSSL=false-->
<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>
编写MyBatis工具类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 + '\'' +
'}';
}
}
编写Mapper接口类
package com.sxau.dao;
import com.sxau.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
List<User> getUserList();
}
编写Mapper.xml配置文件
namespace 十分重要,不能写错!
<?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.sxau.dao.UserMapper">
<select id="getUserList" resultType="com.sxau.pojo.User">
select * from mybatis.user
</select>
</mapper>
编写测试类Junit 包测试
public class MyTest {
@Test
public void test(){
//第一步: 获得sqlSession
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:执行SQL语句 getmapper
// UserDao mapper = sqlSession.getMapper(UserDao.class);
// List<User> 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/java</directory>
<includes>
<include>***.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>***.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
结论
配置文件中namespace中的名称为对应Mapper接口或者Dao接口的完整包名,必须一致!
需求:根据id查询用户
在UserMapper中添加对应方法
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);
}
在UserMapper.xml中添加Select语句
<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);
编写sql语句的时候,需要传递参数类型,参数类型为map
<select id="selectUserByNP2" parameterType="map"
resultType="com.sxau.pojo.User">
select * from user where name = #{username} and pwd = #{pwd}
</select>
在使用方法的时候,Map的 key 为 sql中取的值即可,没有顺序要求!
@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标签差不多!
需求:给数据库增加一个用户
在UserMapper接口中添加对应的方法
//添加用户
int addUser(User user);
在UserMapper.xml中添加insert语句
<!--对象中的属性,可以直接取出来-->
<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标签差不多!
需求:修改用户的信息
在UserMapper接口中添加对应的方法
//修改用户
int updateUser(User user);
在UserMapper.xml中添加update语句
<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删除一个用户
在UserMapper接口中添加对应的方法
根据id删除用户
int deleteUser(int id);
在UserMapper.xml中添加delete语句
<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);
}
}
到此这篇关于Mybatis持久层框架入门之CRUD实例的文章就介绍到这了,更多相关mybatis入门crud内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Mybatis持久层框架入门之CRUD实例代码详解
本文链接: https://lsjlt.com/news/147928.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0