springboot整合篇之数据库连接

1 springboot-jdbc

导入jar包

在springboot2.0以下的版本
        
引入的jbdc和数据库连接池
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>   

配置application.properties

application.properties
#配置数据源
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/chencj_cc_web?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456

指定数据源类型

默认使用的数据源是:org.apache.tomcat.jdbc.pool.DataSource

spring.datasource.type = 默认是: org.apache.tomcat.jdbc.pool.DataSource
                其他   =com.zaxxer.hikari.HikariDataSource
                 =org.apache.commons.dbcp.BasicDataSource
                =org.apache.commons.dbcp2.BasicDataSource
                =Generic DataSource configuration.自定义的数据源类型
​
​
/** 自定义的数据源类型
     * Generic DataSource configuration.
     */
    @ConditionalOnMissingBean(DataSource.class)
    @ConditionalOnProperty(name = "spring.datasource.type")
    static class Generic {
​
        @Bean
        public DataSource dataSource(DataSourceProperties properties) {
            return properties.initializeDataSourceBuilder().build();
        }
    }
​
​
    public DataSource build() {
        Class<? extends DataSource> type = getType();
        //通过反射机制进行自定义数据源类型的创建
        DataSource result = BeanUtils.instantiate(type);
        maybeGetDriverClassName();
        bind(result);
        return result;
    }

数据源初始化:

DataSourceInitializer implements ApplicationListener

方法 1 runSchemaScripts() 运行建表语句 默认加载的 命名对应的schema-*.sql

在application.properties
spring.datasource.schema=对应的建表文件  这是加载自定义的建表

方法2 runDataScripts() 运行插入数据语句 默认加载的 命名对应的data-*.sql

操作数据库:

springboot,提供了模板 JdbcTemplate

对应的方法:

​
    void execute(String sql) throws DataAccessException;
​
    <T> T query(String sql, ResultSetExtractor<T> rse) throws DataAccessException;
​
    void query(String sql, RowCallbackHandler rch) throws DataAccessException;
​
    <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException;
​
    <T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException;
​
    Map<String, Object> queryForMap(String sql) throws DataAccessException;
​
​
    <T> List<T> queryForList(String sql, Class<T> elementType) throws DataAccessException;
​
​
    List<Map<String, Object>> queryForList(String sql) throws DataAccessException;
​
    SqlRowSet queryForRowSet(String sql) throws DataAccessException;
​
    int update(String sql) throws DataAccessException;
​
​
    int[] batchUpdate(String... sql) throws DataAccessException;
​
​
​
    <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action) throws DataAccessException;
​
    <T> T execute(String sql, PreparedStatementCallback<T> action) throws DataAccessException;

自定义数据源:

在application.properties
#   @ConfigurationProperties(prefix="spring.datasource")
#  通过在自定义的数据源上设置, 就可以把下面的值初始化到数据源中
spring.datasource.initialSize=5
spring.datasource.maxActive= 20
spring.datasource.minIdle=5
spring.datasource.maxIdle=5
spring.datasource.maxWait=60000  
​
​
在引入DruidDataSource,
把上述的值,初始化

初始化application.xml 和 web.xml

@Configuration
//加入这个注解就相当于,配置文件的spring中的application.xml的效果
public class DruidSourceConfig {
​
    
    @ConfigurationProperties(prefix="spring.datasource")
    
    @Bean
    //相当于bean标签
    public DataSource getDataSource(){
        return new DruidDataSource();
    }
    
    //配置一个druid的监控器
    //需要servlet,需要一个web.xml但是没有,
    //可以使用ServletRegistrationBean方式实现,
    //和web.xml中servlet标签效果一样
    @Bean
    public ServletRegistrationBean getViewServlet(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(
                new StatViewServlet(),//相当于web.xml中的返回视图类
                "/druid");//相当于 url-pattern
        //可以配置一些初始化can数
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "123456");
        initParameters.put("allow", "");
        //initParameters.put("deny", "");
        
        registrationBean.setInitParameters(initParameters );
        
        
        return registrationBean;
    } 
    //配一个过滤器filter
    //这个filter就是web.xml中的filter标签
    //可以使用FilterRegistrationBean ,实现
    @Bean
    public FilterRegistrationBean webStateFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        //添加过滤的处理类
        registrationBean.setFilter(new WebStatFilter());
        
        //添加初始化参数
        Map<String, String> initParameters = new HashMap<>();
        //过滤器放行的url路径
        initParameters.put("exclusions", "*.js,*.css,/druid/*");
        registrationBean.setInitParameters(initParameters );
        
        
        registrationBean.setUrlPatterns(Arrays.asList("/*"));
        
        return registrationBean;
    }
}

jdbc整合,使用的书库连接池是druid
也做出了druid的后台管理具体的源码地址:https://github.com/nibo123123/springbootJdbc

2 springboot_Mybatis

导包

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
​
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>

Mapper

方式1:注解版

​
​
@Mapper//如果这里不设置可以在朱启动类上设置 @MapperScanner(“对应的mapper包名”)
public interface TAttachMapper2 {
   
​
    @Delete(value="delete from t_attach where id = #{id}")
    int deleteByPrimaryKey(Integer id);
​
    @Insert("insert  into t_attach (id,fname,ftype,fkey,authorId,created) values (#{id},#{fname},#{ftype},#{fkey},#{authorId},#{created})")
    int insert(TAttach record);
/**
 * private Integer id;
​
    private String fname;
​
    private String ftype;
​
    private String fkey;
​
    private Integer authorId;
​
    private Integer created;
 * 
 */
​
    @Select("select * from t_attach")
    List<TAttach> selectAll();
​
    @Select("select * from t_attach where id = #{id}")
    TAttach selectByPrimaryKey(Integer id);
​
​
    //options的注解,表示的是,对于插入返回没有标明主键类型,id ,自增性。并且封装到id中。
    @Options(useGeneratedKeys=true,keyProperty="id")
    @Update("update t_attach set fname=#{fname},ftype=#{ftype},fkey=#{fkey},authorId=#{authorId},created=#{created} where id = #{id}")
    int updateByPrimaryKey(TAttach record);
}

方式2:xml的mapper配置

mapper.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.chencj.springboot_mybatis.mapper.TAttachMapper 对应着Mapper接口的全类名" >
  <resultMap id="BaseResultMap" type="com.chencj.springboot_mybatis.entity.TAttach" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="fname" property="fname" jdbcType="VARCHAR" />
    <result column="ftype" property="ftype" jdbcType="VARCHAR" />
    <result column="fkey" property="fkey" jdbcType="VARCHAR" />
    <result column="author_id" property="authorId" jdbcType="INTEGER" />
    <result column="created" property="created" jdbcType="INTEGER" />
  </resultMap>
    <select id=""></select>
</mapper>

config.xml

​
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 开启驼峰式 映射-->
     <settings>
        <setting name="mapUderscoreToCamelCase" value="true"/>
    </settings>
   <!-- <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/chencj_cc_selfmall?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="chencj/cc/shujuku/mybatis/Sqlmapper.xml"/>
    </mappers>-->
</configuration>

application.properties

#mybatis的mapper。xml  引入到spring中
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
mybatis.config-location=classpath:mybatisConfig.xml

github的地址:https://github.com/nibo123123/springboot-mybatis

3 springboot-jpa

导包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

orm映射

@Entity
@Table(name = "t_user")
public class User {
​
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private String name;
}

dao层设置

接口 继承 CrudRepository<T,Serilize>

可以定制 对应sql的dao处理方

猜你喜欢

转载自blog.csdn.net/sinat_22988423/article/details/88219283
今日推荐