Spring整合MyBatis实现单表crud操作

Spring整合MyBatis实现单表crud操作_第1张图片


基于Spring注解开发

1、创建一个普通的Maven工程

2、向pom.xml文件导入相关依赖


<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>5.2.10.RELEASEversion>
dependency>

<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.16version>
dependency>

<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.47version>
dependency>

<dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatisartifactId>
    <version>3.5.6version>
dependency>

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jdbcartifactId>
    <version>5.2.10.RELEASEversion>
dependency>

<dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatis-springartifactId>
    <version>1.3.0version>
dependency>

<dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.13version>
    <scope>testscope>
dependency>

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>5.2.10.RELEASEversion>
dependency>

3、导入SQL脚本

-- 如果数据库spring_db存在就把他删掉
drop database if exists spring_db;

-- 创建数据库spring_db并设置字符集utf-8
create database spring_db default charset utf8;

-- 使用spring_db数据库
use spring_db;

-- 创建账户表
create table tb_account(
   id int primary key auto_increment comment 'id',
   name varchar(20) comment '账户名称',
   money double comment '账户余额'
);

-- 插入数据
insert into tb_account values(null,'zhangsan',1000),
                             (null,'lucy',3500),
                             (null,'白豆五',7500);

4、编辑pojo类:

/**
 * 账户实体类
 *
 * @author 白豆五
 * @version 2022/12/17 20:49
 * @since JDK8
 */
public class Account implements Serializable {
    private Integer id;  //id
    private String name; //账户名称
    private Double money;//账户余额

    // 无参构造方法
    public Account() {
    }

    // 满参构造方法
    public Account(Integer id, String name, Double money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }

    //getter/setter方法
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    //toString方法
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

5、编写dao接口:

// 操作数据库的接口
public interface AccountDao {

    // 添加账户
    @Insert("insert into tb_account values (null,#{name},#{money})")
    void save(Account account);

    // 根据id删除账户
    @Delete("delete from tb_account where id=#{id} ")
    void deleteById(int id);

    // 根据id修改账户
    @Update("update tb_account set name=#{name},money=#{money} where id=#{id}")
    void update(Account account);

    // 查所有
    @Select("select * from tb_account")
    List<Account> findAll();


    // 根据id查账户
    @Select("select * from tb_account where id=#{id}")
    Account selectById(int id);
}

6、编写service接口和实现类:

public interface AccountService {
    // 添加账户
    void add(Account account);

    // 根据id删除账户
    void deleteById(int id);

    // 根据id修改账户
    void update(Account account);

    // 查所有
    List<Account> findAll();

    // 根据id查账户
    Account selectById(int id);
}
@Service //定义业务层Bean交给Spring容器管理
public class AccountServiceImpl implements AccountService {

    @Autowired //依赖注入(默认按类型自动装配)
    private AccountDao accountDao;

    @Override
    public void add(Account account) {
        accountDao.save(account);
    }

    @Override
    public void deleteById(int id) {
        accountDao.deleteById(id);
    }

    @Override
    public void update(Account account) {
        accountDao.update(account);
    }

    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }

    @Override
    public Account selectById(int id) {
        return accountDao.selectById(id);
    }
}

7、编写JDBC配置类:

public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    // 定义bean,返回dataSource对象
    @Bean //表示当前方法的返回值是一个Bean对象,交给spring容器去管理
    public DataSource dataSource(){
        // 创建Druid数据源对象
        DruidDataSource ds = new DruidDataSource();
        // 配置数据源四个基本参数
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        // 返回bean
        return ds;
    }
}

8、编写mybatis配置类:

public class MyBatisConfig {

    //定义bean,SqlSessionFactoryBean,用于构造sqlSessionFactory对象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        //如何为第三方bean注入资源:只需写入形参即可,spring会自动从ioc容器找DataSource对象并赋值给变量名dataSource。

        // 创建sqlSessionFactoryBean对象
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        // 设置数据源
        ssfb.setDataSource(dataSource);
        // 返回bean
        return ssfb;
    }

    // 定义bean,返回mapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        // 创建MapperScannerConfigurer对象
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        //扫秒包,可以获取包下所有dao接口,配合sqlSessionFactory对象中的sqlSession,创建接口的mapper代理对象,然后放入spring容器中
        msc.setBasePackage("com.baidou.dao");
        // 返回bean
        return msc;
    }
}

9、编写主配置类:

@Configuration //声明当前类是一个spring配置类
@ComponentScan("com.baidou") //组件扫描
@Import({JdbcConfig.class,MyBatisConfig.class}) //导入其他的配置类
@PropertySource({"classpath:db.properties"})    //加载类路径下的配置文件
public class SpringConfig {
    
}

10、编写测试

10.1、测试Druid数据源是否配置成功

public class TestJDBC {
    @Test
    public void testJDBC() {
        // 通过注解方法获取IOC容器
        ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
        DataSource dataSource = app.getBean(DataSource.class);
        System.out.println(dataSource);

        /*
            {
                CreateTime:"2022-12-17 21:46:30",
                ActiveCount:0,
                PoolingCount:0,
                CreateCount:0,
                DestroyCount:0,
                CloseCount:0,
                ConnectCount:0,
                Connections:[]
            }
         */
    }
}

10.2 测试接口

@RunWith(SpringJUnit4ClassRunner.class)//使用Spring整合Junit专用的类加载器
@ContextConfiguration(classes = {SpringConfig.class})
public class AccountServiceTest {

    @Autowired
    private AccountService accountService;


    /**
     * 测试添加账户
     */
    @Test
    public void testAdd() {
        accountService.add(new Account(null, "王五", 500d));
    }

    /**
     * 测试根据id修改账户
     */
    @Test
    public void testUpdate() {
        // 原先信息 id=3 name=”白豆五“ money=7500
        // 修改信息 id=3 name=”白豆五“ money=7000
        accountService.update(new Account(3, "白豆五", 7000d));
    }

    /**
     * 测试查所有
     */
    @Test
    public void findAll() {
        List<Account> list = accountService.findAll();
        list.forEach(System.out::println);
        // Account{id=1, name='zhangsan', money=1000.0}
        // Account{id=2, name='lucy', money=3500.0}
        // Account{id=3, name='白豆五', money=7000.0}
        // Account{id=4, name='王五', money=500.0}
    }

    /**
     * 根据id删除账户
     */
    @Test
    public void testDeleteById() {
        accountService.deleteById(4);

    }

    /**
     * 根据id查账户
     */
    @Test
    public void testSelectById() {
        Account account = accountService.selectById(3);
        System.out.println(account);
        //    Account{id=3, name='白豆五', money=7000.0}
    }
}

项目结构:
Spring整合MyBatis实现单表crud操作_第2张图片

完结撒花❀❀❀❀❀❀

你可能感兴趣的:(Java基础,mybatis,spring,java)