spring基础框架整合mybatis框架连接数据库(set注入,xml配置spring)

项目结构


com.zyj.dao.AccountDao


package com.zyj.dao;

import com.zyj.entity.Account;

import java.util.List;

public interface AccountDao {

    public abstract void save(Account account);

    public abstract void delete(Integer id);

    public abstract void update(Account account);

    public abstract List<Account> findAll();

    public abstract Account findById(Integer id);

}

com.zyj.entity.Account


package com.zyj.entity;

public class Account {

    private Integer 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;
    }

    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;
    }

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

com.zyj.service.Impl.AccountServiceImpl


package com.zyj.service.Impl;

import com.zyj.dao.AccountDao;
import com.zyj.entity.Account;
import com.zyj.service.AccountService;

import java.util.List;

public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

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

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

    @Override
    public void delete(Integer id) {
        accountDao.delete(id);
    }

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

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

com.zyj.service.AccountService


package com.zyj.service;

import com.zyj.entity.Account;

import java.util.List;

public interface AccountService {

    public void save(Account account);

    public void update(Account account);

    public void delete(Integer id);

    public Account findById(Integer id);

    public List<Account> findAll();

}

APP


import com.zyj.entity.Account;
import com.zyj.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class APP {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = (AccountService) ctx.getBean("accountService");
        
        //以查询全部表数据为测试用例
        List<Account> all = accountService.findAll();
        System.out.println(all);
    }
}

src/main/resources/mapper/AccountDao.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.zyj.dao.AccountDao">

    <!--配置根据id查询-->
    <select id="findById" resultType="com.zyj.entity.Account" parameterType="int">
        select *
        from account
        where id=#{id}
    </select>

    <!--配置查询所有-->
    <select id="findAll" resultType="com.zyj.entity.Account">
        select *
        from account
    </select>

    <!--配置保存-->
    <select id="save" parameterType="com.zyj.entity.Account">
        insert into account(name,money)
        values(#{name},#{money})
    </select>

    <!--配置删除-->
    <select id="delete" parameterType="int">
        delete from account
        where id=#{id}
    </select>

    <!--配置更新-->
    <select id="update" parameterType="com.zyj.entity.Account">
        update account
        set name=#{name},money=#{money}
        where id=#{id}
    </select>

</mapper>

src/main/resources/applicationContext.xml


<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        ">

    <!--加载properties配置文件的信息-->
    <context:property-placeholder location="classpath*:*.properties"/>

    <!--加载Druid资源,并配置参数-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <property name="minIdle" value="${jdbc.minIdle}"/>
        <property name="maxWait" value="${jdbc.maxWait}"/>
    </bean>

    <!--配置service作为spring的bean,注入dao-->
    <bean id="accountService" class="com.zyj.service.Impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>

    <!--spring整合mybatis后控制的创建连接用的对象-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.zyj.entity"/>
        <property name="mapperLocations" value="classpath*:mapper/*.xml"/>
    </bean>

    <!--扫描所有的dao接口, 加载mybatis映射配置的扫描,将其作为spring的bean进行管理-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zyj.dao"/>
    </bean>

</beans>

src/main/resources/jdbc.properties


jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@192.168.1.199:1521:orcl
jdbc.username=zyj
jdbc.password=oracle
jdbc.initialSize=30
jdbc.maxActive=100
jdbc.minIdle=30
jdbc.maxWait=10000

 pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zyj</groupId>
    <artifactId>Spring_day01_05_spring整合mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
        <!--oracle-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.1.0</version>
        </dependency>
        <!--mybatis_-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!--spring整合mybatis的jar包,归属于mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
    </dependencies>
</project>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring 整合 MyBatis 操控数据库可以通过以下步骤完成: 1. 配置数据源:在 Spring配置文件中配置数据源,例如: ``` <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="password" /> </bean> ``` 2. 配置 MyBatis:在 Spring配置文件中配置 MyBatis,例如: ``` <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.example.model" /> <property name="mapperLocations" value="classpath:mapper/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper" /> </bean> ``` 3. 编写 Mapper:创建 Mapper 接口并编写 SQL 语句,例如: ``` public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User findById(Long id); @Insert("INSERT INTO user (name, age) VALUES (#{name}, #{age})") int insert(User user); @Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}") int update(User user); @Delete("DELETE FROM user WHERE id = #{id}") int delete(Long id); } ``` 4. 注入 Mapper:在 Service 层中注入 Mapper 并调用相应方法,例如: ``` @Autowired private UserMapper userMapper; public User findById(Long id) { return userMapper.findById(id); } public int insert(User user) { return userMapper.insert(user); } public int update(User user) { return userMapper.update(user); } public int delete(Long id) { return userMapper.delete(id); } ``` 完成以上步骤后,就可以通过 Service 层的方法操控数据库了。例如: ``` User user = userService.findById(1L); System.out.println(user.getName()); User newUser = new User(); newUser.setName("Tom"); newUser.setAge(20); userService.insert(newUser); newUser.setAge(30); userService.update(newUser); userService.delete(2L); ``` 这样就可以查询、新增、修改和删除数据库中的数据了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值