Spring整合MyBatis项目代码示例

文章目录

  • Spring整合MyBatis项目代码示例
    • 1、创建如下结构的项目Spring_MyBatis
    • 2、在pom.xml文件中添加以下依赖并刷新maven
    • 3、在resources文件夹下添加spring等配置文件(applicationContext.xml,db.properties,log4j.properties)
    • 4、mapper层
    • 5、pojo层
    • 6、service层
    • 7、web层
    • 8、建立数据库spring
    • 9、运行结果如下

Spring整合MyBatis项目代码示例

1、创建如下结构的项目Spring_MyBatis

Spring整合MyBatis项目代码示例_第1张图片

2、在pom.xml文件中添加以下依赖并刷新maven

<?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>
    <parent>
        <groupId>cn.fpl</groupId>
        <artifactId>SpringDemo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>Spring_MyBatis</artifactId>

    <properties>
        <!-- 项目源码及编译输出的编码 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!-- 项目编译JDK版本 -->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- Spring常用依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <!-- MySql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.3</version>
        </dependency>
        <!--日志-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.26</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml
                
            
            
                src/main/resources
            
        
    


3、在resources文件夹下添加spring等配置文件(applicationContext.xml,db.properties,log4j.properties)

applicationContext.xml

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

    <context:component-scan base-package="cn.fpl.service"></context:component-scan>

        <!-- 加载配置文件-->
    <context:property-placeholder location="classpath:db.properties" ></context:property-placeholder>
    <!--    配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.user}"/>
        <property name="password" value="${db.password}"/>
    </bean>

    <!--SqlSessionFactory-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--扫描basePackage所指定的包下的所有接口,生成代理类并交给spring的ioc容器管理-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!--  mapper所在的包-->
        <property name="basePackage" value="cn.fpl.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
    </bean>
</beans>

db.properties

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8
db.user=root
db.password=

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

4、mapper层

UserMapper.java

package cn.fpl.mapper;

import cn.fpl.pojo.User;

public interface UserMapper {

    public void addUser(User user);
}

UserMapper.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="cn.fpl.mapper.UserMapper">
    <insert id="addUser" parameterType="cn.fpl.pojo.User">
        insert into t_user(name,money) values(#{name},#{money})
    </insert>
</mapper>

5、pojo层

User.java

/*
 * Copyright (c) 2020, 2024, fpl1116.cn All rights reserved.
 *
 */
package cn.fpl.pojo;

/**
 * 

Project: SpringDemo - User

*

Powered by fpl1116 On 2024-01-05 19:32:30

*

描述:

* * @author fpl1116 [[email protected]] * @version 1.0 * @since 1.8 */ public class User { private Integer id; private String name; private Float money; public User(String name, Float money) { 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 Float getMoney() { return money; } public void setMoney(Float money) { this.money = money; } }

6、service层

UserService.java

public interface UserService {

    void addUser(User user);
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

   @Override
    public void addUser(User user){
        userMapper.addUser(user);
    }

}

7、web层

Client.java

package cn.fpl.web;


import cn.fpl.pojo.User;
import cn.fpl.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = ac.getBean("userServiceImpl", UserService.class);
        userService.addUser(new User("张三丰",4000F));

        userService.addUser(new User("宋远桥",2000F));
    }
}

8、建立数据库spring

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `money` float DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;

9、运行结果如下

Spring整合MyBatis项目代码示例_第2张图片
Spring整合MyBatis项目代码示例_第3张图片

你可能感兴趣的:(JAVA全栈学习路线,#,java,ee,spring,mybatis,java,idea,mysql)