spring如何使用mybatis

不及物动词 其他 32

回复

共3条回复 我来回复
  • worktile的头像
    worktile
    Worktile官方账号
    评论

    在Spring中使用MyBatis,需遵循以下步骤:

    1. 引入依赖:在项目的pom.xml文件中添加MyBatis和MyBatis-Spring的依赖。例如:
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
    
    1. 配置数据源:在Spring的配置文件中,配置数据源,以供MyBatis使用。可以使用Spring提供的DataSource组件,或者使用第三方数据源(如Druid)。

    2. 配置MyBatis:在Spring配置文件中,配置MyBatis的SqlSessionFactory。SqlSessionFactory是MyBatis的核心组件,用于创建SqlSession。需要指定数据源和MyBatis的配置文件。

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>
    
    1. 配置Mapper扫描:在Spring配置文件中,配置Mapper接口的扫描路径。MyBatis通过接口和XML文件进行SQL的映射,使用接口可以提供类型安全的数据库访问。
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.example.mapper" />
    </bean>
    
    1. 编写Mapper接口:创建Mapper接口,定义数据库操作的方法。方法的名称和参数需要与对应的SQL语句保持一致。
    public interface UserMapper {
        User getUserById(Integer id);
        void addUser(User user);
        void updateUser(User user);
        void deleteUser(Integer id);
    }
    
    1. 创建Mapper XML文件:在resources目录下创建与Mapper接口相对应的XML文件,定义SQL语句和映射关系。
    <!-- UserMapper.xml -->
    <mapper namespace="com.example.mapper.UserMapper">
        <select id="getUserById" resultType="com.example.model.User">
            SELECT * FROM user WHERE id = #{id}
        </select>
        <insert id="addUser">
            INSERT INTO user (name, age) VALUES (#{name}, #{age})
        </insert>
        <update id="updateUser">
            UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
        </update>
        <delete id="deleteUser">
            DELETE FROM user WHERE id = #{id}
        </delete>
    </mapper>
    
    1. 使用Mapper:在业务逻辑代码中,通过@Autowired注解注入Mapper接口,即可直接使用。
    @Autowired
    private UserMapper userMapper;
    
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }
    
    public void addUser(User user) {
        userMapper.addUser(user);
    }
    
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }
    
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }
    

    以上就是在Spring中使用MyBatis的基本步骤。通过配置数据源、SqlSessionFactory以及Mapper扫描,结合编写Mapper接口和对应的XML文件,就可以实现方便灵活的数据库操作。

    1年前 0条评论
  • fiy的头像
    fiy
    Worktile&PingCode市场小伙伴
    评论

    使用MyBatis与Spring框架集成可以实现更简单、更方便的数据库访问。下面是Spring如何使用MyBatis的几个步骤:

    1. 配置MyBatis和Spring的依赖关系:在项目的pom.xml文件中添加MyBatis和Spring的相关依赖,例如:
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.3</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <version>2.3.4.RELEASE</version>
    </dependency>
    
    1. 配置数据库连接信息:在Spring的配置文件(如application.properties或application.yml)中配置数据库的连接信息,包括数据库URL、用户名、密码等。

    2. 创建数据源:在Spring的配置文件中配置数据源(DataSource),可以使用Spring提供的数据源,也可以使用第三方数据源,例如Druid。配置数据源的时候,可以将MyBatis的mapper目录添加到MapperLocations中,以便自动扫描并加载XML映射文件。

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/mybatis_demo
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
    mybatis:
      mapper-locations: classpath:mapper/*.xml
    
    1. 创建SqlSessionFactoryBean:在Spring的配置文件中配置SqlSessionFactoryBean,将数据源和MyBatis的配置文件等信息注入到SqlSessionFactoryBean中,并将其交给Spring容器管理。
    @Configuration
    @MapperScan(basePackages = "com.example.demo.mapper", sqlSessionTemplateRef  = "sqlSessionTemplate")
    public class MybatisConfig {
        @Autowired
        private DataSource dataSource;
    
        @Bean(name = "sqlSessionFactory")
        public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
            SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            sessionFactory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
            return sessionFactory;
        }
    
        @Bean(name = "sqlSessionTemplate")
        public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }
    
    1. 创建Mapper接口和Mapper映射文件:使用MyBatis的注解或XML方式配置Mapper接口和Mapper映射文件,用于定义数据库操作的方法和SQL语句。
    public interface UserMapper {
        @Select("SELECT * FROM user WHERE id = #{id}")
        User getUserById(Long id);
    }
    
    <mapper namespace="com.example.demo.mapper.UserMapper">
        <select id="getUserById" parameterType="Long" resultType="com.example.demo.entity.User">
            SELECT * FROM user WHERE id = #{id}
        </select>
    </mapper>
    
    1. 使用Mapper接口:在需要使用数据库操作的地方注入Mapper接口,并调用相应的方法进行数据库操作。
    @Service
    public class UserService {
        @Autowired
        private UserMapper userMapper;
    
        public User getUserById(Long id) {
            return userMapper.getUserById(id);
        }
    }
    

    通过以上步骤,就可以在Spring项目中使用MyBatis进行数据库的访问了。需要注意的是,在Spring Boot项目中,以上的配置可以通过注解的方式实现,也可以通过配置文件的方式实现。具体的配置方式可以根据项目的实际情况选择。

    1年前 0条评论
  • 不及物动词的头像
    不及物动词
    这个人很懒,什么都没有留下~
    评论

    Spring框架是一个非常流行的Java企业级开发框架,而MyBatis是一个开源的持久层框架。将Spring和MyBatis结合使用,可以有效地简化数据库访问的代码,并提供了一种方便的方式来管理数据库事务。

    下面,我将介绍如何在Spring框架中使用MyBatis。

    第一步:配置数据库连接信息

    在Spring的配置文件中,需要配置数据库的连接信息,例如数据库URL、用户名、密码等。可以通过以下方式进行配置:

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

    这里使用了DriverManagerDataSource来配置数据库连接信息,也可以使用其他的数据源,例如BasicDataSource

    第二步:配置SqlSessionFactory

    SqlSessionFactory是MyBatis的核心接口之一,用于创建SqlSession对象。可以通过以下方式进行配置:

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:mappers/*.xml" />
    </bean>
    

    在上述配置中,需要指定数据源和MyBatis的配置文件位置。MyBatis的配置文件中可以进行一系列的配置,例如类型别名、插件、拦截器等。

    第三步:配置MapperScan

    MapperScan是一个注解,用于指定注解了@Mapper的接口所在的包,Spring会自动扫描并注册这些接口的实现类。可以通过以下方式进行配置:

    @Configuration
    @MapperScan("com.example.dao")
    public class AppConfig {
        // ...
    }
    

    需要在Spring配置类上添加@MapperScan注解,并指定注解了@Mapper的接口所在的包。这样,在Spring启动时,会自动扫描并注册这些接口的实现类。

    第四步:注入Mapper接口

    在Service或其他组件中,可以直接注入Mapper接口,并使用MyBatis简化的数据库访问功能。例如:

    @Service
    public class UserService {
        
        @Autowired
        private UserMapper userMapper;
        
        public User getUserById(Long id) {
            return userMapper.getUserById(id);
        }
        
        public void addUser(User user) {
            userMapper.addUser(user);
        }
        
        // ...
    }
    

    在上述代码中,通过@Autowired注解注入了UserMapper接口。然后可以直接使用UserMapper接口中定义的方法来进行数据库访问。

    第五步:配置事务管理器

    使用Spring管理事务可以确保数据库操作的原子性和一致性。可以通过以下方式配置事务管理器:

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    

    在上述配置中,使用DataSourceTransactionManager来管理事务。需要指定数据源。

    第六步:开启事务

    在Service类或其他需要进行事务管理的类中,可以使用@Transactional注解开启事务。例如:

    @Service
    @Transactional
    public class UserService {
        // ...
    }
    

    在上述代码中,使用了@Transactional注解开启事务管理。这样,在Service类中的方法执行时,如果发生异常,将会回滚事务。

    至此,我们已经完成了在Spring中使用MyBatis的配置和使用。通过以上步骤,可以很方便地使用MyBatis进行数据库操作,并且保证了事务的一致性。

    1年前 0条评论
注册PingCode 在线客服
站长微信
站长微信
电话联系

400-800-1024

工作日9:30-21:00在线

分享本页
返回顶部