Mybatis入门教程,实现数据库简单增删改查
程序员文章站
2022-07-10 18:32:41
Mybatis教程(一) 实现数据库简单增删改查(上)首先,我们在数据库中创建一个表,如图接下来,我们创建一个maven项目点击next点击finish在新建的maven项目的pom.xml文件中导入相关jar包 org.mybatis mybatis...
首先,我们在数据库中创建一个表,如图
接下来,我们创建一个maven项目
点击next
点击finish
在新建的maven项目的pom.xml文件中导入相关jar包
<dependencies>
<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.47</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
创建并编写MyBatis核心配置文件
<?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>
<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/cloudhospital?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="167833712"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ltz/dao/UserMapper.xml"/>
</mappers>
</configuration>
接下来创建实体类,首先在java文件夹下创建包
创建User类
编写Mapper接口类
编写增删改查方法
然后在dao包下编写Mapper.xml配置文件
<?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.ltz.dao.UserMapper">
</mapper>
在Mapper.xml中编写sql语句,先实现对所有用户的查询
编写sqlSessionFactory封装类
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();
}
在test包下创建测试类进行测试
@Test
public void test(){
SqlSession sqlSession= MybatisUtils.getSqlSession();
UserMapper usermapper=sqlSession.getMapper(UserMapper.class);
List<User> u=usermapper.getUserList();
for(User user:u){
System.out.println(user);
}
sqlSession.close();
}
但此时运行程序可能会报错,还需在pom.xml文件中加如下代码解决Maven静态资源过滤问题
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
现在运行测试类,查询全部用户成功!
查询指定用户,修改用户信息,删除用户,添加用户功能的实现只需在Mapper.xml中编写相应的sql语句即可,大大减少了代码冗余,下一章我们再来具体实现。
本文地址:https://blog.csdn.net/ltz777/article/details/109275102