SpringBoot中连接MYSQL数据库,并使用JPA进行数据库的相关操作

今天给大家介绍一下如何SpringBoot中连接Mysql数据库,并使用JPA进行数据库的相关操作。

史上最全Java技术栈面试题都在这里面了:Java面试题

步骤一:在pom.xml文件中添加MYSQl和JPA的相关Jar包依赖,具体添加位置在dependencies中,具体添加的内容如下所示。

 <!--数据库相关配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>

步骤二:在application.properties配置文件中加入数据库的相关配置,配置信息如下所示。

spring.datasource.url = jdbc:mysql://localhost:3306/webtest
spring.datasource.username = root
spring.datasource.password = 220316
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

这里给大家解释一下:webtest代表数据库名称、root是用户名、220316是密码

步骤三:编写数据库操作的实体类,实体类具体信息如下所示:

package example.entity;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Date;
@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "name", nullable = true, length = 30)
    private String name;

    @Column(name = "height", nullable = true, length = 10)
    private int height;

    @Column(name = "sex", nullable = true, length = 2)
    private char sex;

    @Temporal(TemporalType.DATE)
    private Date birthday;

    @Temporal(TemporalType.TIMESTAMP)
    private Date sendtime; // 日期类型,格式:yyyy-MM-dd HH:mm:ss

    @Column(name = "price", nullable = true, length = 10)
    private BigDecimal price;

    @Column(name = "floatprice", nullable = true, length = 10)
    private float floatprice;


    @Column(name = "doubleprice", nullable = true, length = 10)
    private double doubleprice;

    public Date getSendtime() {
        return sendtime;
    }

    public void setSendtime(Date sendtime) {
        this.sendtime = sendtime;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public float getFloatprice() {
        return floatprice;
    }

    public void setFloatprice(float floatprice) {
        this.floatprice = floatprice;
    }

    public double getDoubleprice() {
        return doubleprice;
    }

    public void setDoubleprice(double doubleprice) {
        this.doubleprice = doubleprice;
    }

    public User() { }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public User(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }
}

大家这里需要注意的是:实体类中的类名和字段属性都要和数据库中表和字段相互对应。下面给出一张MYSQL-JAVA各种属性的对应关系图:


 

步骤四:编写dao层的数据操作类,dao数据操作类如下所示:

package example.dao;
import example.entity.User;
import org.springframework.data.repository.CrudRepository;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Transactional
public interface UserDao extends CrudRepository<User, Integer> {
    public List<User> findByName(String name);
    public List<User> findBySex(char sex);
    public List<User> findByBirthday(Date birthday);
    public List<User> findBySendtime(Date sendtime);
    public List<User> findByPrice(BigDecimal price);
    public List<User> findByFloatprice(float floatprice);
    public List<User> findByDoubleprice(double doubleprice);
}

大家这里可能会有疑问,为什么要继承CrudRepository<User, Integer>,具体有什么作用呢?

我这里给大家简单的介绍一下JPA中一些常用的用法和使用准则:

1.首先就是要继承CrudRepository这个方法,里面包含的两个参数的具体含义是:第一个参数表示所操作的实体类名称,第二个参数表示实体类中主键的类型。

2.继承完之后就可以使用一些继承自父类的方法了,比如上面所示可以使用findBy+“你要查询的字段名称”,通过这样的方法就可以轻轻松松实现SQL查询的功能了。

说道这里可能大家还是有点迷糊,给大家举一个例子就知道了:

例如上面的findByName(String name)其实等价于SQL语句中的 select *from user where name=?。这样一对比大家是不是马上就清楚这个方法到底代表什么含义了吧。

步骤五:编写controller这个控制类,控制类具体信息如下所示:

package example.controller;
import example.dao.UserDao;
import example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Controller
public class UserController {
    @Autowired
    private UserDao userDao;
    @RequestMapping("/getName")
    @ResponseBody
    public String getByName(String name) {
        List<User> userList = userDao.findByName(name);
        if (userList != null && userList.size()!=0) {
            return "The user length is: " + userList.size();
        }
        return "user " + name + " is not exist.";
    }

    @RequestMapping("/getSex")
    @ResponseBody
    public String getBySex(char sex) {
        List<User> userList = userDao.findBySex(sex);
        if (userList != null && userList.size()!=0) {
            return "The user length is: " + userList.size();
        }
        return "user " + sex + " is not exist.";
    }

    @RequestMapping("/getBirthday")
    @ResponseBody
    public String findByBirthday(String birthday) {
        System.out.println("birthday:"+birthday);
        SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd");
        List<User> userList = null;
        try {
            userList = userDao.findByBirthday(formate.parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (userList != null && userList.size()!=0) {
            return "The user length is: " + userList.size();
        }
        return "user " + birthday + " is not exist.";
    }

    @RequestMapping("/getSendtime")
    @ResponseBody
    public String findBySendtime(String sendtime) {
        System.out.println("sendtime:"+sendtime);
        SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<User> userList = null;
        try {
            userList = userDao.findBySendtime(formate.parse(sendtime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (userList != null && userList.size()!=0) {
            return "The user length is: " + userList.size();
        }
        return "user " + sendtime + " is not exist.";
    }

    @RequestMapping("/getPrice")
    @ResponseBody
    public String findByPrice(BigDecimal price) {
        List<User> userList = null;
        userList = userDao.findByPrice(price);
        if (userList != null && userList.size()!=0) {
            return "The user length is: " + userList.size();
        }
        return "user " + price + " is not exist.";
    }

    @RequestMapping("/getFloatprice")
    @ResponseBody
    public String findFloatprice(float floatprice) {
        List<User> userList = null;
        userList = userDao.findByFloatprice(floatprice);
        if (userList != null && userList.size()!=0) {
            return "The user length is: " + userList.size();
        }
        return "user " + floatprice + " is not exist.";
    }

    @RequestMapping("/getDoubleprice")
    @ResponseBody
    public String findByPrice(double doubleprice) {
        List<User> userList = null;
        userList = userDao.findByDoubleprice(doubleprice);
        if (userList != null && userList.size()!=0) {
            return "The user length is: " + userList.size();
        }
        return "user " + doubleprice + " is not exist.";
    }
}

大家这里可能会有一个很大的疑问,我当初也对这个问题深深的不理,那就是userDao没有实例化为什么能够直接使用呢?

现在我就为大家解释一下为什么会这样:

其实不是这个userDao没有实例化,只是实例化是由系统自动完成的。只要在userDao的上方添加@Autowired属性就可以实现接口自动的实例化了,完全不需要像以前一样需要去写什么userDaoImp之类的实现类了。这样做就可以大大的挺高代码的简易程度,开发速度大大的挺高。

我知道现在可能还会有人问这样一个问题:那就是自动实例化了,可是实例化怎么知道dao类要实现什么的增删改查的功能呀,dao代码里面压根就没说啊?其实有心人可能已经发现了,上一步的时候我们解释了一下findBy+“字段名”的具体作用是什么,这其实就是这个问题的答案。其实dao层中各种方法就是daoimp中各种实现类中的SQl命令,具体是怎么对应的我会再下一节中给大家详细的介绍一下,现在先卖个关子。

步骤六:数据库的表名和字段信息如下所示:

 
 

到这里关于SpringBoot中连接MYSQL数据库,并使用JPA进行数据库的相关操作就介绍完毕了。

如果大家对文章有什么问题或者疑意之类的,可以加我订阅号在上面留言,订阅号上面我会定期更新最新博客。如果嫌麻烦可以直接加我wechat:lzqcode


 

  • 12
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
Spring Boot 提供了 Spring Data JPA 来简化数据库操作,包括连接 MySQL 数据库。下面是连接 MySQL 数据库的步骤: 1. 添加 MySQL 依赖 在 pom.xml 文件添加 MySQL 依赖: ``` <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> ``` 其 `${mysql.version}` 是 MySQL 驱动的版本号,可以根据实际情况进行修改。 2. 配置数据源 在 `application.properties` 文件配置数据源,例如: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 其 `url` 是 MySQL 数据库的地址,`username` 和 `password` 是连接数据库的用户名和密码,`driver-class-name` 是 MySQL 驱动的类名。 3. 创建实体类 创建对应的实体类,例如: ``` @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "age") private Integer age; // getter 和 setter 方法 } ``` 其 `@Entity` 表示该类是一个实体类,`@Table` 指定对应的表名,`@Id` 表示该属性是主键,`@GeneratedValue` 指定主键生成策略,`@Column` 指定对应的字段名。 4. 创建 Repository 创建对应的 Repository 接口,例如: ``` @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 其 `User` 是实体类,`Long` 是主键类型。 现在,就可以在代码使用 `UserRepository` 来进行数据库操作了。例如: ``` @Autowired private UserRepository userRepository; public void saveUser(User user) { userRepository.save(user); } public User getUser(Long id) { return userRepository.findById(id).orElse(null); } public void deleteUser(Long id) { userRepository.deleteById(id); } ``` 以上就是连接 MySQL 数据库的步骤。需要注意的是,如果使用的是 Spring Boot 2.x 版本,需要在 `application.properties` 文件配置 `spring.jpa.hibernate.ddl-auto=update`,可以自动创建对应的数据表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值