spring mysql开发_Spring的数据库开发

spring的jdbcTemplate操作(用在dao层)

spring框架是一个一站式框架,在每一层都提供了解决技术:在Dao层是使用了jdbcTemplate。

spring针对不同的持久化技术都提供了不同的模板。

Spring JDBC

Spring的JDBC模板负责提供数据库资源的管理和错误处理,大大简化了开发人员对数据库操作,使得开发人员可以从繁琐的数据库操作中解脱出来。

Spring jdbcTemplate的解析

针对数据库的操作,Spring框架提供了jdbcTemplate类,该类是Spring框架数据层的基础,其他更高层次的抽象类是构建在JdbcTemplate类之上,可以说,JdbcTemplate是Spring JDBC的核心类。

JdbcTemplata类的继承关系十分简单,它继承了JdbcAccessor抽象类,同时实现了JdbcOperations接口。

52e36af2df1bf5d84643bebc1fc2c22a.png

JdbcAccessor的设计中,对DataSource数据源进行了管理和配置,JdbcOperation接口定义中,定义了通过JDBC操作数据库的基本方法,而核心类JdbcTemplate提供了这些接口方法的实现。

Spring JDBC的配置

Spring JDBC模板主要是有四个包组成,分别是core(核心包),dataSource(数据源包),object(对象包),support(支持包),Spring对数据库的操作都封装在了这几个包中,而想要使用JDBC,就需要对其进行配置,在Spring中,JDBC的配置是在Spring的配置文件applicationContext.xml中完成的,其配置模板如下所示。

http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

dataSource的四个属性:

属性名

含义

driverClassName

所使用的驱动名称,对应驱动JAR包中的Driver类

url

数据源所在的地址

username

访问数据库的用户名

password

访问数据库的密码

Spring JdbcTemplate的常用方法

1.execute():execute(String sql)方法能够完成执行SQL语句的功能,

先创建数据库spring

再在配置文件中配置jdbcTemplate

http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

在创建一个类用来测试是否成功

packagecom.itheima.jdbc;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.springframework.jdbc.core.JdbcTemplate;/*** 使用execute()方法

*@author12428

**/

public classJdbcTemplateTest {public static voidmain(String[] args) {//获取配置文件

ApplicationContext applicationContext=

new ClassPathXmlApplicationContext("applicationContext.xml");//获取JdbcTemplate模板

JdbcTemplate jdbcTemplate=(JdbcTemplate) applicationContext.getBean("jdbcTemplate");//使用execute()方法执行SQL语句,创建用户账号管理表account

jdbcTemplate.execute("create table account("+

"id int primary key auto_increment,"+

"username varchar(50),"+

"balance double)");

System.out.println("账户表account创建成功!");

}

}

测试结果

79f6142fa6ebd7821daa847fbf202f59.png

2.update():update()能完成插入,更新,删除数据的操作。

(1)创建一个类Account类用来对应数据库spring中的表account,如下:

packagecom.itheima.jdbc;/*** 账户类:用来与数据库spring的表account对应

*@author12428

**/

public classAccount {private Integer id; //账户Id

private String username; //用户名

private Double balance; //用户余额

publicInteger getId() {returnid;

}public voidsetId(Integer id) {this.id =id;

}publicString getUsername() {returnusername;

}public voidsetUsername(String username) {this.username =username;

}publicDouble getBalance() {returnbalance;

}public voidsetBalance(Double balance) {this.balance =balance;

}

@OverridepublicString toString() {return "Account [id=" + id + ", username=" + username + ", balance=" + balance + "]";

}

}

(2)创建一个接口类AccountDao,接口中含有几个抽象方法,如下:

packagecom.itheima.jdbc;public interfaceAccountDao {//添加

public intaddAccount(Account account);//更新

public intupdateAccount(Account account);//删除

public int deleteAccount(intid);

}

(3)创建一个类AccountDaoImpl,该类实现了AccountDao接口,如下:

packagecom.itheima.jdbc;importorg.springframework.jdbc.core.JdbcTemplate;public class AccountDaoImpl implementsAccountDao {//声明JdbcTemplate属性及其setter方法,使用setter注入属性

privateJdbcTemplate jdbcTemplate;public voidsetJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate =jdbcTemplate;

}/*** 添加账户 返回一个修改的行数*/@Overridepublic intaddAccount(Account account) {//定义sql语句

String sql = "insert into account(username,balance) value(?,?)";//定义数组来存储sql语句中的参数

Object[] objects = newObject[] { account.getUsername(), account.getBalance() };//执行添加操作,返回的是受SQL影响的记录数

int num = this.jdbcTemplate.update(sql, objects);returnnum;

}/*** 更新账户*/@Overridepublic intupdateAccount(Account account) {//定义SQL

String sql = "update account set username=?,balance=? where id=?";//定义数组来存储sql语句中的参数

Object[] objects = newObject[] { account.getUsername(), account.getBalance(), account.getId() };//执行更新操作,返回的是受SQL语句影响的记录条数

int num = this.jdbcTemplate.update(sql, objects);returnnum;

}/*** 删除用户*/@Overridepublic int deleteAccount(intid) {//定义sql

String sql = "delete from account where id=?";//执行删除操作,返回的是受sql语句影响的记录条数

int num = this.jdbcTemplate.update(sql, id);returnnum;

}

}

(4)设置配置文件applicationContext.xml,如下

http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

(5)创建一个测试类JdbcTemplateTest,使用单元测试,如下:

packagecom.itheima.jdbc;importorg.junit.Test;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.springframework.jdbc.core.JdbcTemplate;public classJdbcTemplateTest {/** public static void main(String[] args) { //获取配置文件 ApplicationContext

* applicationContext= new

* ClassPathXmlApplicationContext("applicationContext.xml"); //获取JdbcTemplate模板

* JdbcTemplate jdbcTemplate=(JdbcTemplate)

* applicationContext.getBean("jdbcTemplate");

* //使用execute()方法执行SQL语句,创建用户账号管理表account

* jdbcTemplate.execute("create table account("+

* "id int primary key auto_increment,"+ "username varchar(50),"+

* "balance double)"); System.out.println("账户表account创建成功!"); }*/

/*** 添加一个用户*/@Testpublic voidaddAccount() {//加载配置文件

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//获取bean

AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");//创建一个用户

Account account = newAccount();

account.setUsername("张三");

account.setBalance(2000.0);//调用方法

int num =accountDao.addAccount(account);//返回一个结果

if (num > 0) {

System.out.println("你已成功添加了" + num + "条数据");

}else{

System.out.println("添加数据失败!");

}

}/*** 更新一个用户*/@Testpublic voidupdateAccount() {//加载配置文件

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//获取bean

AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");//创建一个用户

Account account = newAccount();

account.setId(1);

account.setUsername("李四");

account.setBalance(2000.0);//执行更新方法

int num =accountDao.updateAccount(account);//返回一个结果

if (num > 0) {

System.out.println("你已成功修改了" + num + "条数据");

}else{

System.out.println("添加数据失败!");

}

}/*** 删除一个用户*/@Testpublic voiddeleteAccount() {//加载配置文件

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//获取bean

AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");//执行删除方法

int num = accountDao.deleteAccount(1);//输出结果

if (num > 0) {

System.out.println("你成功删除了" + num + "条数据");

}else{

System.out.println("删除数据失败!");

}

}

}

(6)运行添加方法的结果如下:

0e8241497617e281f910873409a6d91b.png       

d29ffe8fba3302675c750c7eb8bf0faa.png

(7)运行了更新方法的结果如下:

0afb4c6558e5620f8c92e3444e5b340a.png           

68367b72681e6046da6d4d3283c300a6.png

(8)运行了删除方法后的结果如下:

54b15b50f4123a1825586dd988357557.png     

71afde88a3f1d663e96f2f22eebef388.png

3.query():query()方法可以执行查询操作

jdbcTemplate中提供了大量的查询方法,如下是几个常用的查询方法:

方法名

说明

List query(String sql,RowMapper rowMapper)

执行string类型参数提供的的sql语句,并通过RowMapper返回一个List类型的结果

List query(String sql,PreparedStatementSetter pss,RowMapper rowMapper)

根据String类型的参数提供的Sql语句创建的PreparedStatements对象通过RowMapper将结果返回到List中。

List query(String sql,Object[] args,RowMapper rowMapper)

使用Object[]的值来设置sql语句中的参数值,采用RowMapper回调方法直接返回List类型的数据

queryForObject(String sql,RowMapper rowMapper,Object...args)

将args参数绑定到SQL语句中,并通过RowMapper返回一个Object类型的单行记录

queryForList(String sql,Object[] args,class elementType)

该方法可以返回多行数据的结果,但必须是返回列表,elementsType参数返回的是List元素类型

(1)先给数据库中添加几条数据,如下:

d88cfaa2fd5ca4948aeef65ce391a5f8.png

(2)在AccountDao接口中添加两个查询方法:

//通过id查询

public Account queryAccountById(intid);//查询所有的用户

public List queryAllAcount();

(3)在AccounDaoImpl中实现两个查询方法

/*** 根据id来查询账户*/@Overridepublic Account queryAccountById(intid) {//声明sql语句

String sql="select * from account where id=?";//创建一个新的BeanPropertyRowMapper对象,返回一个需要返回的对象类型,不用再手动转换类型

RowMapper rowMapper=new BeanPropertyRowMapper(Account.class);//执行查询语句

return this.jdbcTemplate.queryForObject(sql, rowMapper, id);

}/*** 查询所有的账户*/@Overridepublic ListqueryAllAcount() {//声明sql语句

String sql="select * from account";//创建一个新的BeanPropertyRowMapper对象,返回一个需要返回的对象类型,不用再//手动转换类型

RowMapper rowMapper=new BeanPropertyRowMapper(Account.class);//执行方法

return this.jdbcTemplate.query(sql, rowMapper);

}

(4)在jdbcTemplateTest中添加两个测试方法,如下:

/*** 根据id来查询用户*/@Testpublic voidqueryAccountById() {//加载配置文件

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//获取bean

AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");//执行方法

Account account=accountDao.queryAccountById(1);

System.out.println(account);

}/*** 查询所有的账户*/@Testpublic voidqueryAllAccount() {//获取容器对象

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");//获取对象AccountDao

AccountDao accountDao=(AccountDao) applicationContext.getBean("accountDao");//执行方法

List accounts=accountDao.queryAllAcount();//输出结果

for(Account account:accounts) {

System.out.println(account);}

}

(5)执行第一个查询方法:根据Id来进行查询,结果如下:

7a306312938e8e51dfaf4916638a0032.png

(6)执行第二个插叙方法:查询所有的账户,结果如下:

ebb76190aea48656d0f857a906c5ae09.png

注意:在执行jdbcTemplate查询操作时,如果查询的结果为空,则会抛出一个错误emptyResultDataAccessException异常,这样做的目的是为了防止程序员不对空值进行判断,保证了查程序的健壮性,如果想要查询结果为空时返回一个null而不是异常,则可以在jdbcTemplate返回查询结果的时候捕获异常,然尔返回null,例:

try{

Object obj=jdbcTemplate.queryForObject();

}catch(EmptyResultDataAccessException e){

return null;

}

好的,我可以为您提供关于使用Spring Boot连接MySQL数据库的一些基本信息和步骤。 首先,您需要在您的Spring Boot项目中添加MySQL连接器的依赖。可以在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>{MySQL版本号}</version> </dependency> ``` 请确保将 {MySQL版本号} 替换为您正在使用的MySQL版本号。 接下来,您需要在application.properties文件中配置数据库连接信息。例如: ``` spring.datasource.url=jdbc:mysql://localhost:3306/{数据库名}?useSSL=false&serverTimezone=UTC spring.datasource.username={用户名} spring.datasource.password={密码} spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 请将 {数据库名}、{用户名} 和 {密码} 替换为您的MySQL数据库的实际信息。 最后,您可以通过使用Spring Data JPA或MyBatis等持久化框架来访问数据库。例如,您可以创建一个Person实体类,并使用JPA注解来映射到数据库中的表: ``` @Entity @Table(name = "person") public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "age") private Integer age; // 省略getter和setter方法 } ``` 然后,您可以创建一个PersonRepository接口来访问数据库中的Person表: ``` @Repository public interface PersonRepository extends JpaRepository<Person, Long> { } ``` 现在,您可以使用PersonRepository接口中提供的方法来访问数据库中的数据了,例如: ``` @Autowired private PersonRepository personRepository; public void savePerson(Person person) { personRepository.save(person); } public List<Person> getAllPeople() { return personRepository.findAll(); } ``` 以上就是使用Spring Boot连接MySQL数据库的一些基本信息和步骤。希望对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值