利用java注解方式整合spring和mybatis

资源贴:https://blog.csdn.net/u014527058/article/details/76095875

项目源码:https://github.com/wenrongyao/spring_mybatis

整体工程结构

1、首先先搭建mybatis的部分,配置mybatis的数据源和session工厂

DaoConfig配置类

package com.wry.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * @author rongyao wen
 * @date 2018/7/28
 */
@Configuration
@MapperScan("com.wry.dao")
public class DaoConfig {
    @Value("${jdbc.driverClass}")
    private String driverClass;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Value("${jdbc.url}")
    private String url;

    /**
     * 数据源配置
     *
     * @return
     */
    @Bean
    public DataSource getDataSorce() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 获取sessionFactory
     *
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory getSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(getDataSorce());
        return sqlSessionFactoryBean.getObject();
    }

}

资源文件jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/crawler
jdbc.username=root
jdbc.password=root

2、其次配置spring,并加DaoConfig引入

package com.wry.config;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;

/**
 * @author rongyao wen
 * @date 2018/7/28
 */
@Configuration
/** 引入mybatis的配置 */
@ComponentScan("com.wry.service")
@Import(DaoConfig.class)
public class SpringConfig {
    // 加载资源文件
    @Bean
    public PropertyPlaceholderConfigurer getTestPpc() {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocations(new ClassPathResource("jdbc.properties"));
        return ppc;
    }

}

后面其实就是web的正常开发了

3、service的开发,为了简单起见,这边没有建接口

package com.wry.service;

import com.wry.dao.VideoMapper;
import com.wry.model.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author rongyao wen
 * @date 2018/7/28
 */
@Service
public class VideoService {
    @Autowired
    private VideoMapper videoMapper;

    public Video getVideo(int id) {
        return videoMapper.getVideo(id);
    }
}

4、mapper接口开发,mapper接口有多种方式可以写sql语言,mapper.xml,

@Select @Insert @Delete @Update注解可以直接写sql

@SelectProvider @InsertProvider @DeleteProvider @UpdateProvider 可以通过sql生成类生成sql,这边可以很灵活的定义sql

package com.wry.dao;

import com.wry.model.Video;
import com.wry.provider.VideoProvider;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;

/**
 * @author rongyao wen
 * @date 2018/7/28
 */
@Mapper
public interface VideoMapper {

//    @Select("select v.id from video_weiboall v where v.id = ${value}")
//    public Video getVideo(int id);

    @SelectProvider(type = VideoProvider.class, method = "selectById")
    public Video getVideo(@Param("id") int id);


}

5、sql生成类

package com.wry.provider;

import org.apache.ibatis.annotations.Param;

/**
 * @author rongyao wen
 * @date 2018/7/28
 */
public class VideoProvider {
    public String selectById(@Param("id") int id) {
        StringBuilder sb = new StringBuilder();
        sb.append("select ");
        sb.append("v.id, v.title, v.transpond transpondCount, v.discuss discussCount, v.goodPress goodPressCount ");
        sb.append("from ");
        sb.append("video_weiboall v ");
        sb.append("where v.id= " + id);
        System.out.print(sb.toString());
        return sb.toString();

    }
}

6、实体类

package com.wry.model;

/**
 * @author rongyao wen
 * @date 2018/7/28
 */
public class Video {
    private int id;
    private String title;
    private String discussCount;
    private String transpondCount;
    private String goodPressCount;

    public int getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDiscussCount() {
        return discussCount;
    }

    public void setDiscussCount(String discussCount) {
        this.discussCount = discussCount;
    }

    public String getTranspondCount() {
        return transpondCount;
    }

    public void setTranspondCount(String transpondCount) {
        this.transpondCount = transpondCount;
    }

    public String getGoodPressCount() {
        return goodPressCount;
    }

    public void setGoodPressCount(String goodPressCount) {
        this.goodPressCount = goodPressCount;
    }

    @Override
    public String toString() {
        return "Video{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", discussCount='" + discussCount + '\'' +
                ", transpondCount='" + transpondCount + '\'' +
                ", goodPressCount='" + goodPressCount + '\'' +
                '}';
    }
}

7、测试类

package com.wry;

import com.wry.config.SpringConfig;
import com.wry.service.VideoService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author rongyao wen
 * @date 2018/7/28
 */
public class Main {
    public static void main(String args[]) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        VideoService functionService = context.getBean(VideoService.class);
        System.out.print(functionService.getVideo(1));
        context.close();
    }
}

这边选择AnnotationConfigApplicationContext为spring的容器

结果:

猜你喜欢

转载自blog.csdn.net/wrongyao/article/details/81277066