MyBatis中注解实现CRUD以及其他操作
程序员文章站
2022-06-28 16:49:13
1.结构图2.User实体类package com.itheima.pojo;import java.util.Date;public class User { private Integer id; private String username; private String sex; private String address; private Date birthday; public Integer getId() {...
1.结构图
2.User实体类
package com.itheima.pojo;
import java.util.Date;
public class User {
private Integer id;
private String username;
private String sex;
private String address;
private Date birthday;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", birthday=" + birthday +
'}';
}
}
3.IUserDao接口
package com.itheima.dao;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
/*
Mybatis中针对CRUD一共有四个注解
* @Select() @Insert() @Update() @Delete()
* */
public interface IUserDao {
//查询所有
@Select(value = "select * from user")
List<User> findUser();
//保存一个
@Insert("insert into user(username,birthday,address,sex) values (#{username},#{birthday},#{address},#{sex})")
/*@SelectKey(keyProperty = "id",keyColumn = "id",resultType = Integer.class,before = false,statement = "select last_insert_id()")*/
int insertUser(User user);
//更新一个
@Update("update user set username=#{username},address=#{address},birthday=#{birthday},sex=#{sex} where id=#{id}")
int updateUser(User user);
//删除一个
@Delete("delete from user where id = #{id}")
int deleteUser(Integer id);
//查询根据id
@Select("select * from user where id = #{id}")
User findById(Integer id);
//模糊查询
@Select("select * from user where username like #{username}")
List<User> findByName(String username);
//总条数
@Select("select count(*) from user")
int countTotal();
}
4.外部数据连接
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=123456
5.主配置文件SqlMapConfig.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>
<!--p配置外部数据库-->
<properties resource="jdbcConfig.properties"></properties>
<!--配置别名-->
<typeAliases>
<!--自定义别名 实体类所在位置-->
<package name="com.itheima.pojo"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--指定带有接口注解的位置-->
<mappers>
<package name="com.itheima.dao"/>
</mappers>
</configuration>
6.测试类TestAnn
package com.itheima;
import com.itheima.dao.IUserDao;
import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;
public class TestAnn {
public static void main(String[] args) throws Exception {
//1.获取字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.根据字节输入流构建SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.根据SqlSessionFactory生产一个SqlSession
SqlSession sqlSession = factory.openSession();
//4.使用SqlSession获取Dao的代理对象
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
//5.执行Dao的方法:查询所有
List<User> users = userDao.findUser();
for (User user :users){
System.out.println(user);
}
//6.释放资源..
sqlSession.close();
in.close();
}
}
7.测试类TestCRUD以及其他
package com.itheima;
import com.itheima.dao.IUserDao;
import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class TestCRUD {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private IUserDao userDao;
//初始化
@Before
public void init() throws Exception {
//1.获取字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.根据字节输入流构建SqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
//3.根据SqlSessionFactory生产一个SqlSession
sqlSession = factory.openSession();
//4.使用SqlSession获取Dao的代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}
@After
public void destroy() throws Exception{
//6.释放资源..
sqlSession.commit();
sqlSession.close();
in.close();
}
//查询所有
@Test
public void testFindAll(){
List<User> users = userDao.findUser();
for (User user:users){
System.out.println(user);
}
}
//保存一个
@Test
public void testSave(){
User user = new User();
user.setUsername("张三");
user.setSex("男");
user.setAddress("武汉");
user.setBirthday(new Date());
userDao.insertUser(user);
System.out.println("保存成功");
}
//更新一个
@Test
public void testUpdate(){
User user = new User();
user.setId(1);
user.setUsername("hhhhhhhhhh");
user.setSex("男");
user.setAddress("武汉");
user.setBirthday(new Date());
userDao.updateUser(user);
System.out.println("保存成功");
}
//删除一个
@Test
public void testDelete(){
userDao.deleteUser(9);
System.out.println("删除成功---");
}
//查询一个
@Test
public void testFindOne(){
User user = userDao.findById(8);
System.out.println("查询成功---"+user);
}
//模糊查询
@Test
public void testFindName(){
/*多条数据用list*/
List<User> users = userDao.findByName("%王%");
for (User user:users){
System.out.println("模糊查询成功---"+user);
}
}
//根据id查询一个
@Test
public void testFindById(){
User user = userDao.findById(3);
System.out.println(user);
}
//查询总记录条数
@Test
public void testFindTotal(){
int i = userDao.countTotal();
System.out.println("总条数为="+i);
}
}
8.依赖pom.xml
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
本文地址:https://blog.csdn.net/actores/article/details/110293995
上一篇: 失去华为的订单后,高度依赖美国的台积电除了顺从别无他法
下一篇: iReport使用教程(示例教程)