SpringBootのデータアクセス

レビュー:

SpringBootの基盤

SpringBoot構成

SpringBootログ

SpringBootのWeb開発基盤

SpringBootWeb開発実験

SpringBootWeb開発のフォローアップ処理

SpringBootのDocker準備

JDBCを統合する

新しいSpringBootプロジェクトを作成します。

デフォルトの割り当て:

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.5.133:3306/jdbc
    driver-class-name: com.mysql.jdbc.Driver

テストコード:

@Test
public void contextLoads() throws SQLException{

    System.out.println(dataSource);
    Connection connection = dataSource.getConnection();
    System.out.println(connection);
    connection.close();
}

org.apache.tomcat.jdbc.pool.DataSourceのデータソースがデフォルトで使用されることを説明します

デフォルトのサポート:

org.springframework.boot.autoconfigure.jdbc

    org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration

        org.apache.tomcat.jdbc.pool.DataSource

        org.apache.commons.dbcp.BasicDataSource

        com.zaxxer.hikari.HikariDataSource

        org.apache.commons.dbcp2.BasicDataSource

    カスタムデータタイプ(例:c3p0)

static class Generic {
    Generic() {
    }

    @Bean
    public DataSource dataSource(DataSourceProperties properties) {
    //使用builder创建数据源(自行看源码即可)
        return properties.initializeDataSourceBuilder().build();
    }
}

    org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

        DataSourceInitializer-> ApplicationListener

        runSchemaScripts(); //テーブル作成  ステートメントを実行する

        runDataScripts();  //挿入データステートメントを実行します

        ソースコードは、ファイルにschema-*。sql(デフォルトはschema.sql)という名前を付けて、認識されるようにクラスパスに配置するだけでよいことを示しています

        構成方法を使用することもできます: spring.datasource.schema = classpath:department.sql

    カスタムデータソースを構成します。

<!--引入阿里的druid数据源
-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.8</version>
</dependency>

    構成ファイル: spring.datasource.type = com.alibaba.druid.pool.DruidDataSource

    #その他の構成
    initialSize:5 
    minIdle:5
    maxActive:20
    maxWait:60000
    timeBetweenEvictionRunsMillis:60000
    minEvictableIdleTimeMillis:300000 validateQuery:
    SELECT 1 FROM DUAL
    testWhileIdle:to true
    testOnBorrow:false
    testOnReturn:false
    poolPreparedStatements:to true
    #監視統計インターセプトを構成しますインターフェイスsqlはカウントできず、「     wall 」がファイアウォール
    フィルターに使用されます:stat、wall、log4j
maxPoolPreparedStatementPerConnectionSize:20
    useGlobalDataSourceStat:true
    connectionProperties:druid.stat.mergeSql = true; druid.stat.slowSqlMillis = 500

    新しい構成クラスDruidConfig:

@Configuration
public class DruidConfig {

    @ConfigurationProperties("spring.datasource")
    @Bean
    public DruidDataSource druid(){
        return new DruidDataSource();
    }

    /**
     * 配置druid的监控
     */
    //1.配置一个管理后台的servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "root");
        initParams.put("allow", "");  //默认允许所有
        initParams.put("deny", "173.0.0.88");  //拒绝本机访问
        bean.setInitParameters(initParams);
        return bean;
    }

    //2.配置web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*");  //排除指定拦截地址
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

    访问 http:// localhost:8080 / druid / login.html

MyBatisを統合する

1)注釈バージョン方式

新しいSpringBootプロジェクトを作成します。

JDBCと同様に、構成ファイルとdruid構成クラスが必要です

データベースを操作するための新しいマッパーインターフェイス:

@Mapper//指定这是一个操作数据库的mapper
public interface DepartmentMapper {

    //将sql语句直接写在方法上
    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int delDept(Integer id);

    @Options(useGeneratedKeys = true, keyProperty = "id") //使用自增的id, 并指定对象中的id是主键
    @Insert("insert into department(departmentName) value(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department d set d.departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

ps:現時点では、インターフェイスで@Mapperの注釈を使用する必要がありますが、マッパーインターフェイスが多い場合は、それぞれに注釈を付けるのが面倒です。@ MapperScan( "<package path>"を使用できます。 )注:スタートアップクラスでは、パッケージパス内のすべてのマッパークラスをスキャンできます。

新しいControllerクラスを作成します。

@RestController
public class DeptController {

    @Autowired
    DepartmentMapper departmentMapper;

    @GetMapping("dept/{id}")
    public Department getDeptById(@PathVariable("id") Integer id){
        return departmentMapper.getDeptById(id);
    }

    @GetMapping("/insertDept")
    public Department insertDept(Department department){
        departmentMapper.insertDept(department);
        return department;
    }
}

http:// localhost:8080 / insertDept / departmentName = ZhaoLiuにアクセスします

キャメルケースマッチングモードを変更します。新しいカスタム構成クラスMyBatisConfigを作成します。 

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

データベースがxxx_xxxで、エンティティクラスがxxxXxxの場合でも、マッチングを実行できます。

2)設定ファイル方式

1)ディレクトリ構造:

①EmployeeMapper.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="org.mybatis.example.BlogMapper">
    <select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>

変更後:

<?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.idea.springboot.mapper.EmployeeMapper">
    <select id="getEmpById" resultType="com.idea.springboot.bean.Employee">
        select * from employee where id=#{id}
    </select>

    <insert id="insertEmp">
        insert into employee(lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

②mybatis-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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>

 変更後:

<?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="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

コントローラテスト:

@RestController
public class EmpController {

    @Autowired
    EmployeeMapper employeeMapper;

    @GetMapping("/emp/{id}")
    public Employee getEmpById(@PathVariable("id") Integer id){
        return employeeMapper.getEmpById(id);
    }
}

JPAを統合する

SpringData:統合データアクセス用のAPI(他のJPAの再カプセル化)

ステップ:

①エンティティクラスを記述し、データベーステーブルとのマッピング関係を設定します。

@Entity//表示JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user")//和指定的数据库表对应(如果省略, 默认表名就是类名小写user)
public class User {

    @Id//表明这是主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
    private Integer id;

    @Column(name = "last_name",length = 50)//表明这是和数据库表中的一列
    private String lastName;
    
    @Column//省略默认列名就是属性名
    private String email;

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

②daoインターフェースを記述し、エンティティークラスに対応するデータベーステーブルを操作します。このインターフェースは、JpaRepositoryインターフェースを継承する必要があります。

public interface UserRepository extends JpaRepository<User, Integer> {
}

③基本構成(その他は自動構成)

spring:
  jpa:
    hibernate:
#      update: 更新或创建数据库表(没有则创建, 有则更新)
      ddl-auto: update
#      true: 控制台展示sql
    show-sql: true

④コントローラーテスト

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id){
        User user = userRepository.findOne(id);
        return user;
    }

    @GetMapping("/user")
    public User insertUser(User user){
        User user1 = userRepository.save(user);
        return user1;
    }
}

おすすめ

転載: blog.csdn.net/ip_JL/article/details/84947135