0% found this document useful (0 votes)
122 views39 pages

JDBC and MyBatis

The document discusses data access with Spring JDBC and MyBatis frameworks. It provides an overview of Spring JDBC, including how to configure data sources and use the JdbcTemplate to execute queries. It then covers Spring MyBatis, describing how it automates SQL mapping and offers alternatives to JDBC and Hibernate. Configuration steps for MyBatis include setting the data source, adding the MyBatis dependency, and implementing repositories with SQL annotations.

Uploaded by

Rofak Vkm1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views39 pages

JDBC and MyBatis

The document discusses data access with Spring JDBC and MyBatis frameworks. It provides an overview of Spring JDBC, including how to configure data sources and use the JdbcTemplate to execute queries. It then covers Spring MyBatis, describing how it automates SQL mapping and offers alternatives to JDBC and Hibernate. Configuration steps for MyBatis include setting the data source, adding the MyBatis dependency, and implementing repositories with SQL annotations.

Uploaded by

Rofak Vkm1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Data Access with MyBatis

JdbcTemplate & MyBatis

Prepared by Spring Team


Content

⎆ Spring JDBC
⎆ Spring MyBatis

2
Spring JDBC

⎊ JDBC stands for Java Database Connectivity.


⎊ JDBC is a standard Java API for database-independent connectivity between the Java
programming language and a wide range of database.
⎊ JDBC needs the configuration of Spring Boot for access to the specific of database server such
as PostgreSQL, MySQL, H2, …
⎊ You’ll need the spring-boot-starter-jdbc dependency as the primary one as well as a dependency
for the database server (e.g. postgres, mysql, ...).
⎊ Spring Boot configures the data source automatically for us by providing the properties in a
properties file.

3
Spring JDBC (cont.)

Main Dependencies:

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

4
Spring JDBC (cont.)

⎊ Java Configuration
@Configuration
public class JdbcConfiguration {

@Bean
public DataSource myPostgresDb() {
DataSourceBuilder dataSource = DataSourceBuilder.create();
dataSource.driverClassName("org.postgresql.Driver");
dataSource.url("jdbc:postgresql://localhost:5432/postgres");
dataSource.username("postgres");
dataSource.password("qwer");
return dataSource.build();
}

}
5
Spring JDBC (cont.)

⎊ Properties File Configuration


spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=qwer

6
Spring JDBC (cont.)

⎊ The JdbcTemplate is the main API through which you’ll access most of the functionality:
⚬ Creation and closing of connections
⚬ Executing statements and stored procedure calls
⚬ Iterating over the ResultSet and returning results
⎊ Example

public List<NoteEntity> findAll() {


return jdbcTemplate.query(
"select * from notes",
(rs, rowNum) -> new NoteEntity(
rs.getInt("id"), rs.getString("title"), rs.getString("desc")
)
);
} 7
Spring JDBC (cont.)

⎊ Example

public class NoteEntity {

private int id;


private String title;
private String desc;

public NoteEntity(int id, String title, String desc) {


this.id = id;
this.title = title;
this.desc = desc;
}
}

8
Spring JDBC (cont.)

⎊ Example

public interface NoteRepository {


List<NoteEntity> findAll();
}

9
Spring JDBC (cont.)

⎊ Example
@Repository
public class JdbcNoteRepository implements NoteRepository {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public List<NoteEntity> findAll() {
return jdbcTemplate.query(
"select * from notes",
(rs, rowNum) -> new NoteEntity(
rs.getInt("id"),
rs.getString("title"),
rs.getString("desc")
)
);
}
} 10
Spring JDBC (cont.)

⎊ Example
@RestController
@RequestMapping("/db")
public class NoteController {

private NoteRepository noteRepository;


@Autowired
public void setNoteRepository(NoteRepository noteRepository) {
this.noteRepository = noteRepository;
}

@GetMapping()
public List<NoteEntity> findAllNotes() {
return noteRepository.findAll();
}

}
11
Spring JDBC (cont.)

⎊ Testing with Postman


⎊ GET :
⚬ http://localhost:8080/db
⎊ Result :
[
{
"id": 1,
"title": "CentOS 7",
"desc": "Understanding basic of CentOS 7"
}
]
12
Spring MyBatis

⎊ MyBatis is a open-source, lightweight, persistence framework.


⎊ It is an alternative to JDBC and Hibernate.
⎊ It automates the mapping between SQL databases and objects in Java.
⎊ A significant difference between MyBatis and other persistence frameworks is that MyBatis
emphasizes the use of SQL, while other frameworks such as Hibernate typically uses a custom
query languages (HQL/EJBQL).
⎊ MyBatis is a fork of IBATIS 3.0 and is maintained by a team that includes the original creators
of IBATIS.

13
Spring MyBatis (cont.)

⎊ MyBatis comes with the following design philosophies:


⚬ Open source
⚬ Support ORM
⚬ Simplicity
⚬ Fast Development
⚬ Portability
⚬ Independent Interface
⚬ Stored procedures
⚬ Inline SQL
⚬ Dynamic SQL
14
Spring MyBatis (cont.)
Diagram of Application Server

15
Spring MyBatis (cont.)

⎊ Benefit of MyBatis usage:


⚬ Analytic fetch queries
⚬ Stored procedures and dynamic SQL
⚬ Support complicated search queries, where search criteria are dynamic, and paging of
results.
⚬ It is faster than Hibernate at SELECTS.

16
Spring MyBatis (cont.)

⎊ Maven Dependency
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>

⎊ Quick Setup
⚬ MyBatis-Spring-Boot-Starter will:
◦ Auto detect an existing DataSource
◦ Will create and register an instance of a SqlSessionFactory passing that DataSource
as an input using the SqlSessionFactoryBean
17
Spring MyBatis (cont.)

⎊ Step 1 - DataSource Configuration (Java or Properties)


@Configuration
public class DatabaseConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new
DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("org.postgresql.Driver");
driverManagerDataSource.setUrl("jdbc:postgresql://localhost:5432/postgres");
driverManagerDataSource.setUsername("postgres");
driverManagerDataSource.setPassword("qwer");

return driverManagerDataSource;
}
}
18
Spring MyBatis (cont.)

⎊ Step 1 - DataSource Configuration (Java or Properties)


spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=qwer

19
Spring MyBatis (cont.)

⎊ Step 2 - MyBatis Configuration


@Configuration
@MapperScan("com.chhaya.mybatis.repository")
public class MyBatisConfig {
private DataSource dataSource;
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Bean
public DataSourceTransactionManager dataSourceTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean() {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
} 20
Spring MyBatis (cont.)

⎊ Step 3 - Implement using POJO


⚬ Create Repository (interface)
⚬ Using MyBatis annotation such as @Select, @Delete, @Insert, @Update, … to process
your SQL
⚬ Example of NoteRepository

@Repository
public interface NoteRepository {
@Select("select * from notes")
List<Note> findAll();
}

21
Spring MyBatis (cont.)

⎊ Step 3 - Implement using POJO (cont.)


⚬ Create Service class to process business logic
⚬ Example of NoteService
@Service
public class NoteService {
private NoteRepository noteRepository;
@Autowired
public void setNoteRepository(NoteRepository noteRepository) {
this.noteRepository = noteRepository;
}
public List<Note> findAllNotesAndAddPrefix(String prefix) {
List<Note> notes = noteRepository.findAll();
for (Note note : notes) {
note.setTitle(prefix + "-" + note.getTitle());
}
return notes;
}
} 22
Spring MyBatis (cont.)

⎊ Step 3 - Implement using POJO (cont.)


⚬ Create Controller class to response the data back to client
⚬ Example of NoteController
@RestController
@RequestMapping("notes")
public class NoteController {
private NoteService noteService;
@Autowired
public void setNoteService(NoteService noteService) {
this.noteService = noteService;
}

@GetMapping
public List<Note> findAll() {
return noteService.findAllNotesAndAddPrefix("KSHRD");
}
} 23
Spring MyBatis (cont.)

⎊ Step 3 - Implement using POJO (cont.)


⚬ Testing with Postman to see the result
⚬ GET - http://localhost:8080/notes
[
{
"id": 1,
"title": "KSHRD-CentOS 7",
"desc": "Understanding basic of CentOS 7"
},
{
"id": 2,
"title": "KSHRD-Ubuntu",
"desc": "Testing server"
}
] 24
Spring MyBatis (cont.)

⎊ Example of CRUD process in MyBatis


@Repository
public interface NoteRepository {
@Select("select * from notes")
List<Note> findAll(); // select all record
@Select("select * from notes where id = #{id}")
Note findById(int id); // select a record by id
@Delete("delete from notes where id = #{id}")
int deleteById(int id); // delete a record by id
@Insert("insert into notes (title, description) " +
"values (#{title}, #{description})")
int insert(Note note); // insert a new record
@Update("update notes set title = #{title}, description = #{description} " +
"where id = #{id}")
int update(int id, Note note); // update an existing record
}
25
Spring MyBatis (cont.)

⎊ Example of testing CRUD operation in SpringBootApplication


@SpringBootApplication
public class MybatisApplication implements CommandLineRunner {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private NoteRepository noteRepository;
@Autowired
public void setNoteRepository(NoteRepository noteRepository) {
this.noteRepository = noteRepository;
}
@Override
public void run(String... args) throws Exception {
Note note = noteRepository.findById(3);
int delete = noteRepository.deleteById(1);
int insert = noteRepository.insert(new Note("Ubuntu", "Testing server"));
int update = noteRepository.update(3, new Note("Korea Software Global Aid", "NGO"));
logger.info("Finding -> {}", note);
logger.info("Deleting -> {}", delete);
logger.info("Inserting -> {}", insert);
logger.info("Updating -> {}", update);
}
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
} 26
Spring MyBatis (cont.)

⎊ Old Data ⎊ New Data

⎊ Logger

27
Spring MyBatis (cont.)

⎊ MyBatis Annotations
⚬ @Insert, @Select, @Update, @Delete - those annotations represent SQL statements to
be executed by calling annotated class as the previous example.
⚬ @Results - it is a list of result mappings that contain the details of how the database
columns are mapped to Java class properties and it uses @Result to map a single instance
of Result out of list of @Results.
@Select("select * from notes")
@Results({
@Result(property = "noteId", column = "note_id"),
@Result(property = "noteTitle", column = "note_title"),
@Result(property = "noteCategory", javaType = List.class)
})
List<Note> findAll();
28
Spring MyBatis (cont.)

⎊ MyBatis Annotations (cont.)


⚬ @Many - it specifies a mapping of one object to a collection of other objects.
@Select("select * from notes")
@Results({
@Result(property = "noteId", column = "note_id"),
@Result(property = "noteTitle", column = "note_title"),
@Result(property = "noteCategory",
javaType = List.class,
column = "note_category",
many=@Many(select = “getCategories”))
})
List<Note> findAll();

@Select("select * from notes")


List<Categories> getCategories();

29
Spring MyBatis (cont.)

⎊ MyBatis Annotations (cont.)


⚬ @One - it specifies the one to one mapping relationship between objects and it similars to
@Many annotation.
⚬ @MapKey - this is used to convert the list of records Map of records with the key as
defined by value attribute.
@Select("select * from notes")
@MapKey("noteId")
Map<Integer, Note> getAllNotes();

⚬ @Options - this annotation specifies a wide range of switches and configuration to be


defined so that instead of defining them on other statements we can use @Options to
30
define them
Spring MyBatis (cont.)

⎊ Dynamic SQL is a very powerful feature provided by MyBatis.


⎊ With this, we can structure our complex SQL with accuracy.
⎊ It eliminates the traditional JDBC code which we write the large SQL statements and this is
very error prone and very difficult to debug.
⎊ Dynamic SQL provides all the SQL constructs as a class.
⎊ Example
⚬ SELECT, WHERE etc
⎊ With this, we can dynamically change the generation of WHERE clause.

31
Spring MyBatis (cont.)

⎊ Example of using dynamic SQL in the application:


@SelectProvider(type = NoteProvider.class, method = "getNoteByTitle")
Note getNoteByTitle(String title);
⎊ We have specified a class and a method name which actually constructs and generate the final
SQL:

public class NoteProvider {


// ...
public String getNoteByTitle(String title){
return new SQL() {{
SELECT("*");
FROM("notes");
WHERE("title like #{title} || '%'");
}}.toString();
}
} 32
Spring MyBatis (cont.)

⎊ Example of creating NoteProvider class


public class NoteProvider {

private String tableName = "notes"; // define the table name

// select data from dynamic column


public String selectSingleColumn(String singleColumnName) {
return new SQL() {{
SELECT(singleColumnName);
FROM(tableName);
}}.toString();
}

}
33
Spring MyBatis (cont.)

⎊ Example of adding one more method to NoteProvider class:


public class NoteProvider {
private String tableName = "notes"; // define the table name

public String selectNotesByWhere(@Param("note") Note note) {


return new SQL(){{
SELECT("id", "title", "description");
FROM(tableName);
// dynamically change the generation of WHERE clause
if (!ObjectUtils.isEmpty(note)) {
if (note.getId() != 0) {
WHERE("id=#{note.id}");
} else if (!StringUtils.isEmpty(note.getTitle())) {
WHERE("title=#{note.title}");
} else {
WHERE("1=1");
}
}
}}.toString();
}
34
}
Spring MyBatis (cont.)

⎊ Example of using dynamic SQL in Repository


@Repository
public interface NoteRepository {

@SelectProvider(type = NoteProvider.class, method = "selectSingleColumn")


List<String> selectSingleColumn(String singleColumnName);

@SelectProvider(type = NoteProvider.class, method = "selectNotesByWhere")


List<Note> selectNotesByWhere(@Param(value = "note") Note note);

35
Spring MyBatis (cont.)

⎊ Example of using dynamic SQL with SpringBootApplication:


@SpringBootApplication
public class MainApplication implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
String columnName = "title"; // you can change column name here
List<String> data = noteRepository.selectSingleColumn(columnName);

for (String d : data) {


System.out.println("Data --> " + "[" + columnName + "] == " + d);
}
}
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
} 36
Spring MyBatis (cont.)

⎊ Example of using dynamic SQL with SpringBootApplication: (cont.)


@SpringBootApplication
public class MainApplication implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {

Note note = new Note();


note.setTitle("Ubuntu");

System.out.println(noteRepository.selectNotesByWhere(note));
}

public static void main(String[] args) {


SpringApplication.run(MybatisApplication.class, args);
}
} 37
Spring MyBatis (cont.)

⎊ Stored Procedure Support


⚬ We can also execute the stored procedure using @Select annotation.
⚬ We need to pass the name of the stored procedure, the parameter list and use an explicit
Call or SELECT to that procedure:
⚬ Example
@Repository
public interface NoteRepository {

// select_all_notes is a stored procedure in the database server


@Select(value= "SELECT * FROM select_all_notes()")
List<Note> selectAllNotes();

}
38
THANKS!
Please try hard to study..!

39

You might also like