• Springboot+mybatis+dbcp+mysql简单集成


    1、添加依赖

            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.1.1</version>
            </dependency>
    
            <dependency>
                <groupId>commons-dbcp</groupId>
                <artifactId>commons-dbcp</artifactId>
                <version>1.4</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    

    2、在src/main/resources建立config目录,创建db.properties:

    #jdbc
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://118.25.190.197:3306/test?useUnicode=true&characterEncoding=utf8
    jdbc.username=root
    jdbc.password=******
    jdbc.maxActive=2335
    jdbc.maxIdel=120
    jdbc.maxWait=100
    

    3、在src/main/java创建包cn.mmweikt.config.database,创建3个类:

    package cn.mmweikt.producer.config.database;
    
    import org.apache.commons.dbcp.BasicDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    @Configuration
    //这个注解导入刚才增加的jdbc配置文件
    @PropertySource("classpath:config/db.properties")
    public class DataSourceConfiguration {
       @Value("${jdbc.driver}")
       private String driver;
       @Value("${jdbc.url}")
       private String url;
       @Value("${jdbc.username}")
       private String username;
       @Value("${jdbc.password}")
       private String password;
       @Value("${jdbc.maxActive}")
       private int maxActive;
       @Value("${jdbc.maxIdel}")
       private int maxIdel;
       @Value("${jdbc.maxWait}")
       private long maxWait;
    
       
       @Bean
       public BasicDataSource dataSource(){
           BasicDataSource dataSource = new BasicDataSource();
           dataSource.setDriverClassName(driver);
           dataSource.setUrl(url);
           dataSource.setUsername(username);
           dataSource.setPassword(password);
           dataSource.setMaxActive(maxActive);
           dataSource.setMaxIdle(maxIdel);
           dataSource.setMaxWait(maxWait);
           dataSource.setValidationQuery("SELECT 1");
           dataSource.setTestOnBorrow(true);
           dataSource.setDefaultAutoCommit(true);
           return dataSource;
       }
    }
    
    package cn.mmweikt.producer.config.database;
    
    import javax.sql.DataSource;
    
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    import org.springframework.transaction.PlatformTransactionManager;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    import org.springframework.transaction.annotation.TransactionManagementConfigurer;
    
    /**
    * @author kibana
    *
    */
    @Configuration
    //加上这个注解,使得支持事务
    @EnableTransactionManagement
    public class MyBatisConfig implements TransactionManagementConfigurer {
       @Autowired
       private DataSource dataSource;
    
       @Override
       public PlatformTransactionManager annotationDrivenTransactionManager() {
            return new DataSourceTransactionManager(dataSource);
       }
    
       @Bean(name = "sqlSessionFactory")
       public SqlSessionFactory sqlSessionFactoryBean() {
           SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
           bean.setDataSource(dataSource);
    
           try {
               return bean.getObject();
           } catch (Exception e) {
               e.printStackTrace();
               throw new RuntimeException(e);
           }
       }
    
       @Bean
       public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
           return new SqlSessionTemplate(sqlSessionFactory);
       }
    }
    
    package cn.mmweikt.producer.config.database;
    
    import org.mybatis.spring.mapper.MapperScannerConfigurer;
    import org.springframework.boot.autoconfigure.AutoConfigureAfter;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
    * 扫描mybatis的接口
    * 
    * @author kibana
    *
    */
    @Configuration
    // 因为这个对象的扫描,需要在MyBatisConfig的后面注入,所以加上下面的注解
    @AutoConfigureAfter(MyBatisConfig.class)
    public class MyBatisMapperScannerConfig {
       @Bean
       public MapperScannerConfigurer mapperScannerConfigurer() {
           MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
           //获取之前注入的beanName为sqlSessionFactory的对象
           mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
           //指定xml配置文件的路径
           mapperScannerConfigurer.setBasePackage("cn.mmweikt.mapping");
           return mapperScannerConfigurer;
       }
    }
    

    3、创建cn.mmweikt.mapper包,添加接口:

    package cn.mmweikt.producer.mapper;
    
    import java.util.List;
    import java.util.Map;
    
    import cn.mmweikt.producer.entity.Order;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    @Mapper
    //在这里,使用@Mapper注解来标识一个接口为MyBatis的接口,MyBatis会自动寻找这个接口
    public interface TestDao {
    
       //@Select("select * from wx_userinfo;")
       //public Mapfind();
       
       //@Insert("insert into wx_userinfo(openid,status,nickname,sex,city,province,country,headimgurl,subscribe_time) "+
       //        "values(#{id},1,'nick',1,'city','provi','contr','img',now())")
       //public int insert(@Param("id")int id);
    
       @Select("select id,name as body,message_id as messageId from t_order")
       public List<Order> queryAll();
    }
    

    4、创建数据库表t_order(id,name,message_id)和与之对应的实体类,cn.mmweikt.entity.Order:

    -- ----------------------------------
    -- Table structure for t_order
    -- ----------------------------------
    DROP TABLE IF EXISTS `t_order`;
    CREATE TABLE `t_order` (
      `id` varchar(128) NOT NULL,
      `name` varchar(128) DEFAULT NULL,
      `message_id` varchar(128) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    package cn.mmweikt.producer.entity;
    
    import java.io.Serializable;
    
    public class Order implements Serializable {
    
        private static final long serialVersionUID = -5803120402049000020L;
        private String id;
        private String messageId;
        private String body;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getMessageId() {
            return messageId;
        }
    
        public void setMessageId(String messageId) {
            this.messageId = messageId;
        }
    
        public String getBody() {
            return body;
        }
    
        public void setBody(String body) {
            this.body = body;
        }
    }
    

    5、创建cn.mmweikt.controller测试。

  • 相关阅读:
    Best Cow Line(POJ No.3617)
    迷宫的最短路径
    Lak3 Counting(POJ No.2386)
    【日志】-2013.11.02
    用Python实现gmail邮箱服务,实现两个邮箱之间的绑定(上)
    用Python实现gmail邮箱服务,实现两个邮箱之间的绑定(下)
    【日志】-2013.11.01
    (转载)HTML与XHTML有什么区别
    (转载)linux环境变量
    转载-KMP算法前缀数组优雅实现
  • 原文地址:https://www.cnblogs.com/kibana/p/9658009.html
Copyright © 2020-2023  润新知