0

I am using Spring JPA. I have a master and n number of slaves. I'd like the read operations to be done on a slave, and the write operations to be done on the master.

How can I achieve that in SpringBoot? what're my options?

Some codes:

@Entity(name = "Team")
@Data
public class Team {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
}


@Repository
public interface TeamRepository extends JpaRepository<Team, Integer> {
    Optional<List<Team>> findByName(String name);
}

and I connect to DB like this

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/team
spring.datasource.username={$username}
spring.datasource.password={$passwod}
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
#spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
server.port=9990
spring.logging.level.org.hibernate.SQL=debug
spring.jpa.show-sql=true
Marco Dinatsoli
  • 10,322
  • 37
  • 139
  • 253
  • 1
    I don't think this is supported, however you can have two datasources configured in the application. Also, instead of using the term `slave`, you can use `secondary`, `worker`, `replica`. – aksappy Mar 24 '21 at 20:22
  • @aksappy this is a normal use case. Are you saying spring boot is not being deployed in any real production product? – Marco Dinatsoli Mar 24 '21 at 21:48
  • 1
    I doubt your requirement is a close representation of how most systems are designed. Spring can have multiple datasources configured and you can programmatically allow read or write in many ways, but spring cant be configured to make that decision out of the box. Check this page on how it is done using txn routing. https://vladmihalcea.com/read-write-read-only-transaction-routing-spring/ . That being said, I will dig more and come back if I find anything. – aksappy Mar 25 '21 at 01:52

0 Answers0