当先锋百科网

首页 1 2 3 4 5 6 7

创建java项目,包及相关类

案例结构图
在这里插入图片描述

向pom.xml文件导入依赖包

<dependencies>
        <!--mybatis包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>

        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!--spring包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.9.RELEASE</version>
            <scope>test</scope>
        </dependency>


        <!--spring与mybatis的桥接-->
        <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <!--数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
        </dependency>


        <!--事务管理包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>


<!--        &lt;!&ndash; https://mvnrepository.com/artifact/org.springframework/spring-jdbc &ndash;&gt;-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
    </dependencies>

编写实体类Account

public class Account {
private Integer id;
private String name;
private Float money;

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 Float getMoney() {
    return money;
}

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

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

}

编写Dao接口(Mybatis注解的方式)

@Repository
public interface AccountDao {

    /**
     * 根据id查找用户
     * @param id
     * @return
     */
    @Select("select * from account where id = #{id}")
    public Account findById(Integer id);


    /**
     * 根据姓名查找用户
     * @param name
     * @return
     */
    @Select("select * from account where name = #{name}")
    public Account findByName(String name);


    /**
     * 更新账户信息
     * @param account
     * @return
     */
    @Update("update account set money=#{money} where name=#{name}")
    public int updateAccount(Account account);


}

编写业务层代码

public interface AccountService {
    /**
     * 查找用户
     * @param id
     * @return
     */
    public Account findById(Integer id);

    /**
     * 转账业务
     * @param from 转账人
     * @param to 接收人
     * @param money 转账金额
     */
    public void trans(String from,String to,Float money);
}

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;


    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public void trans(String from, String to, Float money) {
        //1.查找转账人是否存在
        Account fromAccount = accountDao.findByName(from);
        if (fromAccount==null){
            System.out.println("转账人不存在,请检查账户...");
            return;
        }
        //2.查找接收人是否存在
        Account toAccount = accountDao.findByName(to);
        if (toAccount==null){
            System.out.println("接收人不存在,请检查账户...");
            return;
        }
        //3.转账
        //扣款
        fromAccount.setMoney(fromAccount.getMoney()-money);
        accountDao.updateAccount(fromAccount);

        //手动制造一个异常
        int i=1/0;

        //进账
        toAccount.setMoney(toAccount.getMoney()+money);
        accountDao.updateAccount(toAccount);
    }

    public static void main(String[] args) {
    }
}



编写mybatis配置⽂件

在Resources⽬录下创建⼀个mybatisConfig.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>
<!--配置环境-->
<environments default="development"> <environment id="development">
    <!--事务管理器-->
    <transactionManager type="JDBC"/>
    <!--连接池技术-->
    <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </dataSource>
</environment>
</environments> <mappers>
    <!--扫包-->
    <package name="com.dgut.dao"/>
</mappers>
</configuration>

创建spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.dgut"/>
   
    <!--spring容器接管sqlsessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatisConfig.xml"/>
    </bean>

</bean>

将mybatis配置整合到spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.dgut"/>
    <!--spring管数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>	
    </bean>

    <!--spring容器接sqlsessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>


    <!--spring配置mybatis扫包路径-->
    <bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dgut.dao"/>
    </bean>
</bean>

测试

public class MyTest {


    @Test
    public void testMybatis() throws IOException {
        //1.读取mybatis配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybatisConfig.xml");
        //2.创建sessionFactory,用来产生session
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.创建会话session
        SqlSession session = sessionFactory.openSession();
        //4.获取AccountDao的实现
        AccountDao accountDao = session.getMapper(AccountDao.class);
        //5.测试
        Account account = accountDao.findById(6);
        System.out.println(account);
        Account jack = accountDao.findByName("jack");
        System.out.println(jack);

    }
}

用注解的方式配置mybatis配置信息

创建SpringConfiguration

@Configuration
@ComponentScan("com.dgut")
@MapperScan(basePackages = "com.dgut.dao")
public class SpringConfiguration {

    @Bean
    public DruidDataSource druidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///spring");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(){
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(druidDataSource());
        sqlSessionFactory.setConfigLocation(new ClassPathResource("mybatisConfig.xml"));
        return sqlSessionFactory;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.dgut.dao");
        return mapperScannerConfigurer;
    }
}