springboot資料庫連線-jdbc,druid,mybatis,JPA
JDBC
spring: datasource: # 資料來源基本配置 username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/jdbc?&useSSL=false&serverTimezone=UTC //校準時差 initialization-mode: always //Spring Boot2.x 執行schema.sql初始化資料庫
1.DataSourceInitializer:ApplicationListener 作用:
schema‐*.sql(sql建表語句)、data‐*.sql(sql資料有關語句)
預設規則:schema.sql,schema‐all.sql;
可以使用:schema:
‐ classpath:department.sql 指定位置
2.操作資料庫:自動配置了JdbcTemplate操作資料庫:
@Controller public class HelloController { @Autowired JdbcTemplate jdbcTemplate; @ResponseBody @GetMapping("/query") public Map<String,Object> map(){ List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from department"); return list.get(0); } }
Druid
Druid是一個具有成套的監控與安全的資料來源。 可以監控資料庫訪問效能,內建提供了一個功能強大的StatFilter外掛,能夠詳細統計SQL的執行效能,這對於線上分析資料庫訪問效能有幫助。
1.引入Druid
進入maven倉庫https://mvnrepository.com/,搜尋Druid,複製所需的版本。新增到springboot的pom.xml中。
2.在application.xml配置檔案中更改資料來源型別:
type: com.alibaba.druid.pool.DruidDataSource
3.新增資料來源屬性:
關於齊進左對齊可用快捷鍵:shift+tab
# 資料來源其他配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true # 配置監控統計攔截的filters,去掉後監控介面sql無法統計,'wall'用於防火牆 filters: stat,wall,log4j2 maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
由於這些屬性在DataSourceProperties並沒有,所並不能繫結到DataSourceProperties中,預設不起作用。要起作用需自己建立它的配置類:
匯入druid資料來源//配置Druid的監控 //1.配置一個管理後臺的Servlet
@Configuration public class DruidConfig {
//將自定義的屬性繫結進去 @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druid(){ return new DruidDataSource(); }
@Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); Map<String ,String> initParams = new HashMap<>(); initParams.put("loginUsername","admin"); //設定登入名稱 initParams.put("loginPassword","123456"); //設定登入密碼 initParams.put("allow",""); //預設是允許所有訪問 initParams.put("deny","10.81.255.181"); //設定禁止訪問物件 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; } }
Mybatis
使用springboot,勾選mybatis自動會配置
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency>
1.註解版
//指定這是一個操作資料庫的mapper
@Mapper public interface DepartmentMapper { @Select("select * from department where id = #{id}") public Department getDeptById(Integer id); @Delete("delete from department where id = #{id}") public void delDeptById(Integer id); @Options(useGeneratedKeys = true,keyProperty = "id") //獲取自增id @Insert("insert into department(department_name) values(#{departmentName})") public void insertDept(Department department); @Update("update department set department_name = #{departmentName} where id = #{id}") public void updateDept(Department department); }
若需開啟駝峰命名,自定義MyBatis的配置規則;給容器中新增一個ConfifigurationCustomizer:
@org.springframework.context.annotation.Configuration public class MybatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer(){ return new ConfigurationCustomizer(){ @Override public void customize(Configuration configuration) { configuration.setMapUnderscoreToCamelCase(true); } }; } }使用MapperScan批量掃描所有的Mapper介面:
package com.example.springbootdatamybatis; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan(value = "com.example.springbootdatamybatis.mapper") //mapper包下的其所有都自動添加了註解 @SpringBootApplication public class SpringbootDataMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringbootDataMybatisApplication.class, args); } }
此時在mapper中的註解@Mapper可以註釋掉
2.配置檔案版
建立mybatis的配置檔案:xml形式。 mybatis程式碼都託管在github下:https://github.com/search?q=mybatis
在建立好的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>
在建立好的sql對映檔案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="com.example.springbootdatamybatis.mapper.EmployeeMapper"> //和介面繫結 <!--public Employee getEmpById(Integer id); public void insertEmp(Employee employee);--> <select id="getEmpById" resultType="com.example.springbootdatamybatis.bean.Employee"> //配置方法 select * from employee where id = #{id} </select> <insert id="insertEmp" useGeneratedKeys="true" keyProperty="id"> insert into employee(lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#{dId}) </insert> </mapper>
在application.xml中配置:
mybatis: config-location: classpath:mybatis/mybatis_config.xml //指定全域性配置檔案的位置 mapper-locations: classpath:mybatis/mapper/*.xml //指定sql對映檔案的位置
若需開啟駝峰命名法,在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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/> //駝峰命名法開啟
</settings>
</configuration>
更多操作參考:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfifigure/
JPA
整合SpringData JPA:ORM(Object Relational Mapping)
1)、編寫一個實體類(bean)和資料表進行對映,並且配置好對映關係://使用JPA註解配置對映關係2)、編寫一個Dao介面來操作實體類對應的資料表(Repository):
@Entity //告訴JPA這是一個實體類(和資料表對映的類)
@Table(name = "tbl_user") //@Table來指定和哪個資料表對應;如果省略預設表名就是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;
}
//繼承JpaRepository來完成對資料庫的操作 public interface UserRepository extends JpaRepository<User,Integer> { }3)、基本的配置JpaProperties:
spring:
jpa: hibernate: # 更新或者建立資料表結構 ddl-auto: update # 控制檯顯示SQL show-sql: true