spring boot使用mysql

    使用数据库是开发基本应用的基础。借助于开发框架,我们已经不再编写原始的访问数据库的代码,也不用调用JDBC或者连接池等诸如此类的被称作为底层的代码了。spring boot包含了一个功能强大的资源库,为使用spring boot的开发者提供了更加简便的接口进行访问。

    一、使用MySQL:

        对于传统关系型数据库来说,spring boot使用JPA资源库来实现对数据库的操作,JPA就是为POJO提供持久化的标准规范,即将java的普通对象通过对象关系映射ORM持久化到数据库中。

    1、MySQL依赖配置:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

    2、实体建模:

        首先创建一些普通对象,用来与数据库的表建立映射关系,然后使用JPA对数据库进行增删改查等存取操作。        

@Entity
@Table(name = "user")
public class User implements java.io.Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createdate;

    public User() {
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Date getCreatedate() {
        return createdate;
    }

    public void setCreatedate(Date createdate) {
        this.createdate = createdate;
    }
}

    3、实体持久化

    以上已使用普通对象(POJO)与数据库建立映射关系(ORM),接下来使用JPA实现持久化。

    User实体使用JPA进行持久化如下所示。它是一个接口,并继承于JPA资源库JpaRepository接口,使用注解@Repository将这个接口也定义为一个资源库,使他能被其他程序引用,并为其他程序提供存取数据库的功能。

    

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    User findByNameLike(String name);
    User readByName(String name);
    List<User> getByCreatedateLessThan(Date star);
}
    这样就实现存取数据库的功能了,现在可以对数据库进行增删改查、分页查询、指定排序的字段等操作了。

    使用JPA不需要对接口有任何实现的代码,也不需要SQL语句。JpaRepository继承于PagingAndSortingRepository,提供了分页和排序功能,PagingAndSortingRepository继承于CrudRepository,提供了简单的增删改查功能。

    JPA还提供了一些自定义声明方法的规则,如,findBy、readBy,getBy作为方法名的前缀,拼接实体类中的属性字段,首字母大写,并可选拼接一些SQL查询关键字来组合成一个查询方法。如上面代码。

    4、测试验证:

    增加一个JPA配置类,其中@EnableTransactionManagement 启用了JPA的事务管理;@EnableJpaRepositories启用了JPA资源库并指定了上面定义的接口资源库的位置;@EntityScan指定了定义实体的位置,他将导入我们定义的实体。

@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "dbdemo.**.repository")
@EntityScan(basePackages = "dbdemo.**.entity")
public class JpaConfiguration {

    @Bean
    PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
        return new PersistenceExceptionTranslationPostProcessor();
    }

}

    需要本地安装MySQL数据库,之后创建一个数据库,可以自定义命名为“shenchong”,配置密码123456。数据库的表结构不用创建,在程序运行的时候将会按照实体的定义自动创建。

    然后在application.yml中添加配置,用来设置数据源和JPA的工作模式:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/shenchong?useSSL=false
    username: root
    password: 123456
  jpa:
    database: MYSQL
    show-sql: true
  #Hibernate ddl auto (validate|create|create-drop|update)
    hibernate:
      ddl-auto: update
      naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect

    5、编写测试程序:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {JpaConfiguration.class})
public class MysqlTest {
    private static Logger logger = LoggerFactory.getLogger(MysqlTest.class);

    @Autowired
    UserRepository userRepository;

    @Before
    public void initData(){
        userRepository.deleteAll();

        User user = new User();
        user.setName("user");
        user.setCreatedate(new Date());

        userRepository.save(user);
        Assert.notNull(user.getId());
    }

    @Test
    public void findPage(){
        Pageable pageable = new PageRequest(0, 10, new Sort(Sort.Direction.ASC, "id"));
        Page<User> page = userRepository.findAll(pageable);
        Assert.notNull(page);
        for(User user : page.getContent()) {
            logger.info("====user==== user name:{}",user.getName());
        }
    }


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Spring Boot解析MySQL binlog,你需要使用一个名为"debezium"的开源库,它提供了一个用于解析MySQL binlog的模块。 以下是使用Spring Boot和Debezium解析MySQL binlog的步骤: 1. 添加Debezium依赖 在pom.xml文件添加以下依赖: ```xml <dependency> <groupId>io.debezium</groupId> <artifactId>debezium-embedded</artifactId> <version>1.6.0.Final</version> </dependency> ``` 2. 配置Debezium 添加以下配置类: ```java @Configuration public class DebeziumConfig { @Bean public Configuration debeziumConfiguration() { return Configuration.create() .with("connector.class", "io.debezium.connector.mysql.MySqlConnector") .with("offset.storage", "org.apache.kafka.connect.storage.FileOffsetBackingStore") .with("offset.storage.file.filename", "/path/to/offset/file/offset.dat") .with("offset.flush.interval.ms", 60000) .with("name", "my-sql-connector") .with("database.hostname", "localhost") .with("database.port", 3306) .with("database.user", "root") .with("database.password", "password") .with("database.server.id", 1) .with("database.server.name", "my-app-connector") .with("database.whitelist", "my-db") .build(); } @Bean public EmbeddedEngine debeziumEngine() { return EmbeddedEngine.create() .using(debeziumConfiguration()) .notifying(record -> { String recordValue = record.value() != null ? record.value().toString() : null; System.out.println(recordValue); }) .build(); } } ``` 这个配置类定义了Debezium连接到MySQL所需的配置参数,并配置了一个EmbeddedEngine,它将接收来自Debezium的记录并将其打印到控制台。 3. 启动Debezium 启动应用程序并等待一段时间,以便Debezium连接到MySQL并开始发送来自binlog的记录。当记录被发送时,它们将被打印到控制台。 以上就是使用Spring Boot和Debezium解析MySQL binlog的步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值