原生的JDBC
默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源;
数据源的相关配置都在DataSourceProperties里面;
相关配置(application.yml)
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/springboot
driver-class-name: com.mysql.jdbc.Driver
启动主程序,即可连接上数据库
其中两个方法:
1)、runSchemaScripts();运行建表语句;在启动后就会自动执行
默认规则(名字是这样才能够被识别):schema.sql,schema-all.sql;
自定义:需要在application.yml或者application.properties文件中进行配置
schema:
- classpath:department.sql//指定位置
2)、runDataScripts();运行插入数据的sql语句;
@Controller
public class JdbcController {
@Autowired
JdbcTemplate jdbcTemplate;
@ResponseBody
@GetMapping("/hello")
public Map<String,Object> connectJdbc(){
List<Map<String,Object>> list = jdbcTemplate.queryForList("SELECT * from department");
return list.get(0);
}
}
整合Druid数据源
1、添加依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
配置相关数据
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/springboot
driver-class-name: com.mysql.jdbc.Driver
#使用type来改变数据源
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
//这个是自定义的数据源配置
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")//将以spring.datasource为前缀的属性(即上面所说到的数据源的其他配置)绑定到Druid数据库连接池的属性上
@Bean
public DataSource druid(){
return new DruidDataSource();
}
}
配置druid的监控
1、配置一个管理后台的Servlet
2、配置一个web监控的filter
**注意:使用中发现一个错误就是配置好了,但是进入不了后天管理页面,发现在Servlet中忘记写映射路径**
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
注意:一定要加上注解,记得加注解
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//管理后台的的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<String,String>();
//设置登录后台的用户名和密码
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");
//下面这个方法的参数需要一个集合
bean.setInitParameters(initParams);
return bean;
}
//配置一个web监控的filter
@Bean
public FilterRegistrationBean webStateFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<String,String>();
//排除拦截静态资源的请求
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
//设置拦截的请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
注解版mybatis使用
创建一个Mapper,这个mapper是接口,根据注解来进行增删改查
@Mapper
public interface DepartmentMapper {
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
}
@Options(useGeneratedKeys = true,keyProperty = "id")
useGeneratedKeys :是否使用自增主键,keyProperty:使用哪一个属性作为主键
使用了这个注解以后,返回的数据就直接可以查到主键
@GetMapping("/dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}
比如这个例子,在页面返回的json数据中,就会含有主键信息
注意:当我们的数据库中的属性的名字和实体类的名字不相同时,这个时候就不能够将数据封装到实体类中,这个时候需要使用进行设置来开启驼峰命名规则映射
@org.springframework.context.annotation.Configuration
public class MybatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
//开启驼峰命名法映射规则
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
当Mapper特别多的时候,每一个类都需要加@Mapper注解,此时就可以在主程序上加上@MapperScan注解即可,指定扫描的包名
@MapperScan(value = "atguigu.mapper")
使用配置文件方式
首先全局配置文件
<?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>
</configuration>
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.atguigu.mapper.EmployeeMapper">
<select id="getEmpById" parameterType="int" resultType="com.atguigu.bean.Employee">
select * from employee where id = #{id}
</select>
<insert id="insertEmp" parameterType="com.atguigu.bean.Employee">
INSERT INTO employee(lastName,email,gender,dId) VALUES (#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>
重要一点就是:一定要在配置中指定文件的位置,即在application.yml或者application.properties中指定mybatis相关配置文件的位置
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
SpringBoot与数据访问整合JPA
JPA是基于ORM(对象关系映射)
1、配置数据源
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/springboot
driver-class-name: com.mysql.jdbc.Driver
2、编写一个实体类(bean)和数据表进行映射,并且配置好映射关系
这个实体类和主程序放在同一个包下,因为默认扫描主程序所在包下的所有组件
//告诉JPA这是一个实体类,(和数据表映射的类)
@Entity
//指明和哪一个数据表映射,如果不写,默认表名是类名小写
@Table(name = "tbl_user")
public class User {
@Id //表明这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//表示自增
private Integer id;
@Column(name = "last_name") //表示是数据库的一个列,也可以不指定列明,那么就是默认是属性名
private String lastName;
private String email;
public void setId(Integer id) {
this.id = id;
}
。。。。。
3、编写一个Dao接口来操作实体类对应的数据表(repository)
//继承JpaRepository<T,ID>来完成对数据库的操作,第一个参数是实体类,第二个是该实体类的主键的数据类型
public interface UserRepository extends JpaRepository<User,Integer>{
}
4、在yml中进行配置,创建数据库表
jpa:
hibernate:
#更新或者创建数据库表
ddl-auto: update
#每次增删改查的时候在控制台显示sql
show-sql: true
5、使用controller进行测试(这里面已经自动生成了一些查询方法,有些类似于逆向工程)
@RestController
public class UserController {
@Autowired
UserRepository userRepository;
@GetMapping("user/{id}")
public User getUserById(@PathVariable("id") Integer id){
User user = userRepository.findOne(id);
return user;
}
@GetMapping("user")
public User InsertUser(User user){
userRepository.save(user);
return user;
}
}