SpringBoot與數(shù)據(jù)訪問

<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>
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.15.22:3306/jdbc
    driver-class-name: com.mysql.jdbc.Driver

效果:

? 默認是用org.apache.tomcat.jdbc.pool.DataSource作為數(shù)據(jù)源;

? 數(shù)據(jù)源的相關(guān)配置都在DataSourceProperties里面;

自動配置原理:

org.springframework.boot.autoconfigure.jdbc:

1算灸、參考DataSourceConfiguration壁却,根據(jù)配置創(chuàng)建數(shù)據(jù)源语卤,默認使用Tomcat連接池眶根;可以使用spring.datasource.type指定自定義的數(shù)據(jù)源類型豺谈;

2比藻、SpringBoot默認可以支持铝量;

org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource银亲、BasicDataSource慢叨、

3、自定義數(shù)據(jù)源類型

/**
 * Generic DataSource configuration.
 */
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {

   @Bean
   public DataSource dataSource(DataSourceProperties properties) {
       //使用DataSourceBuilder創(chuàng)建數(shù)據(jù)源务蝠,利用反射創(chuàng)建響應(yīng)type的數(shù)據(jù)源拍谐,并且綁定相關(guān)屬性
      return properties.initializeDataSourceBuilder().build();
   }

}

4、DataSourceInitializer:ApplicationListener

? 作用:

? 1)轩拨、runSchemaScripts();運行建表語句践瓷;

? 2)、runDataScripts();運行插入數(shù)據(jù)的sql語句亡蓉;

默認只需要將文件命名為:

schema-*.sql搭综、data-*.sql
默認規(guī)則:schema.sql区丑,schema-all.sql嘱蛋;
可以使用   
    schema:
      - classpath:department.sql
      指定位置

5叫潦、操作數(shù)據(jù)庫:自動配置了JdbcTemplate操作數(shù)據(jù)庫

2、整合Druid數(shù)據(jù)源

導(dǎo)入druid數(shù)據(jù)源
@Configuration
public class DruidConfig {

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

    //配置Druid的監(jiān)控
    //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","123456");
        initParams.put("allow","");//默認就是允許所有訪問
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2巫员、配置一個web監(jiān)控的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;
    }
}

3、整合MyBatis

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
搜狗截圖20180305194443.png

步驟:

? 1)甲棍、配置數(shù)據(jù)源相關(guān)屬性(見上一節(jié)Druid)

? 2)、給數(shù)據(jù)庫建表

? 3)赶掖、創(chuàng)建JavaBean

4)感猛、注解版

//指定這是一個操作數(shù)據(jù)庫的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 int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

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

問題:

自定義MyBatis的配置規(guī)則;給容器中添加一個ConfigurationCustomizer奢赂;

@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接口陪白;
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
    }
}

5)、配置文件版

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml  指定sql映射文件的位置

更多使用參照

http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

2)膳灶、整合SpringData JPA

JPA:ORM(Object Relational Mapping)咱士;

1)、編寫一個實體類(bean)和數(shù)據(jù)表進行映射轧钓,并且配置好映射關(guān)系序厉;

//使用JPA注解配置映射關(guān)系
@Entity //告訴JPA這是一個實體類(和數(shù)據(jù)表映射的類)
@Table(name = "tbl_user") //@Table來指定和哪個數(shù)據(jù)表對應(yīng);如果省略默認表名就是user;
public class User {

    @Id //這是一個主鍵
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主鍵
    private Integer id;

    @Column(name = "last_name",length = 50) //這是和數(shù)據(jù)表對應(yīng)的一個列
    private String lastName;
    @Column //省略默認列名就是屬性名
    private String email;

2)毕箍、編寫一個Dao接口來操作實體類對應(yīng)的數(shù)據(jù)表(Repository)

//繼承JpaRepository來完成對數(shù)據(jù)庫的操作
public interface UserRepository extends JpaRepository<User,Integer> {
}

3)弛房、基本的配置JpaProperties

spring:  
 jpa:
    hibernate:
#     更新或者創(chuàng)建數(shù)據(jù)表結(jié)構(gòu)
      ddl-auto: update
#    控制臺顯示SQL
    show-sql: true
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市而柑,隨后出現(xiàn)的幾起案子文捶,更是在濱河造成了極大的恐慌,老刑警劉巖媒咳,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件粹排,死亡現(xiàn)場離奇詭異,居然都是意外死亡涩澡,警方通過查閱死者的電腦和手機顽耳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人斧抱,你說我怎么就攤上這事常拓。” “怎么了辉浦?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵弄抬,是天一觀的道長。 經(jīng)常有香客問我宪郊,道長掂恕,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任弛槐,我火速辦了婚禮懊亡,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘乎串。我一直安慰自己店枣,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布叹誉。 她就那樣靜靜地躺著鸯两,像睡著了一般。 火紅的嫁衣襯著肌膚如雪长豁。 梳的紋絲不亂的頭發(fā)上钧唐,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天,我揣著相機與錄音匠襟,去河邊找鬼钝侠。 笑死,一個胖子當(dāng)著我的面吹牛酸舍,可吹牛的內(nèi)容都是我干的帅韧。 我是一名探鬼主播,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼啃勉,長吁一口氣:“原來是場噩夢啊……” “哼弱匪!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起璧亮,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤萧诫,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后枝嘶,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體帘饶,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年群扶,在試婚紗的時候發(fā)現(xiàn)自己被綠了及刻。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片镀裤。...
    茶點故事閱讀 40,503評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖缴饭,靈堂內(nèi)的尸體忽然破棺而出暑劝,到底是詐尸還是另有隱情,我是刑警寧澤颗搂,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布担猛,位于F島的核電站,受9級特大地震影響丢氢,放射性物質(zhì)發(fā)生泄漏傅联。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一疚察、第九天 我趴在偏房一處隱蔽的房頂上張望蒸走。 院中可真熱鬧,春花似錦貌嫡、人聲如沸比驻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽别惦。三九已至,卻和暖如春弦撩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背论皆。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工益楼, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人点晴。 一個月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓感凤,卻偏偏與公主長得像,于是被迫代替她去往敵國和親粒督。 傳聞我的和親對象是個殘疾皇子陪竿,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內(nèi)容