12 Ocak 2018 Cuma

MyBatis

MyBatis Nedir
Açıklaması şöyle
MyBatis is a first-class persistence framework with support for custom SQL, stored procedures, and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces, and Java POJOs (Plain Old Java Objects) to database records.

MyBatis is a fork of iBATIS 3.0 and is maintained by a team that includes the original creators of iBATIS.
Spring
Gradle ile şu satırı dahil ederiz
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2'
Bir tane repository yaratırız.
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository {

    String SELECT_FROM_BOOK_WHERE_ID = "SELECT * FROM book WHERE id = #{id}";
    String SELECT_FROM_BOOK = "select * from book";

    @Select(SELECT_FROM_BOOK)
    List<Book> findAll();

    @Select(SELECT_FROM_BOOK_WHERE_ID)
    Book findById(long id);

    @Select("SELECT * FROM book WHERE title = #{title}")
    Book findByTitle(String title);

    @Delete("DELETE FROM book WHERE id = #{id}")
    boolean deleteById(long id);

    @Insert("INSERT INTO book(title, isbn, description, page, price) " +
            " VALUES (#{title}, #{isbn}, #{description}, #{page}, #{price})")
    void insert(Book book);

  @Update("Update book set title=#{title}, " +
 " isbn=#{isbn}, description=#{description}, page=#{page}, price=#{price} where id=#{id}")
  int update(Book book);
}
Kullanmak için şöyle yaparız
import org.springframework.util.ObjectUtils;

@RequiredArgsConstructor
@Service
public class BookServiceImpl implements BookService {

  private final BookRepository repository;

  @Override
  public Book create(Book book) {
    Book bookById = getByTitle(book.getTitle());
    if(!ObjectUtils.isEmpty(bookById)){
       throw new DuplicateException(...);
    }
    repository.insert(book);
    return getByTitle(book.getTitle());
  }

  @Override
  public List<Book> getAll(){
    return repository.findAll();
  }

  @Override
  public Book getOne(long id) {
    Book book = repository.findById(id);
    if(ObjectUtils.isEmpty(book)){
      throw new DataNotFoundException(...);
    }
    return book;
  }

  @Override
  public void deleteById(long id) {
    boolean isDeleted = repository.deleteById(id);
    if(!isDeleted){
      throw new BadRequestException(...);
    }
  }

  @Override
  public Book getByTitle(String title) {
    return repository.findByTitle(title);
  }
}
SessionFactory Sınıfı
Şu satırı dahil ederiz
import org.mybatis.spring.SqlSessionFactoryBean;
insert
Örnek - Batch Insert
Şöyle yaparsak yanlış olur
SqlSession session = sessionFactory.openSession(ExecutorType.BATCH);
for (Model model : list) {
  session.insert("insertStatement", model);
}
session.flushStatements();
Çünkü bu yöntem PreparedStatement'ı tekrar kullanmak yerine her seferinden yeni bir Statement yaratıyor. Eğer yazılacak satır sayısı çok fazlaysa şöyle yaparız
SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
try {
  SimpleTableMapper mapper = session.getMapper(SimpleTableMapper.class);
  List<SimpleTableRecord> records = ...
 
  BatchInsert<SimpleTableRecord> batchInsert = insert(records)
    .into(simpleTable)
    .map(id).toProperty("id")
    .map(firstName).toProperty("firstName")
    .map(lastName).toProperty("lastName")
    .map(birthDate).toProperty("birthDate")
    .map(employed).toProperty("employed")
    .map(occupation).toProperty("occupation")
    .build()
    .render(RenderingStrategy.MYBATIS3);
 
  batchInsert.insertStatements().stream().forEach(mapper::insert);
 
  session.commit();
} finally {
  session.close();
}
JDBC kullansaydık şöyle olurdu
Connection connection = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/mydb?" + 
"useUnicode=true&characterEncoding=UTF-8&" + 
"useServerPrepStmts=false&rewriteBatchedStatements=true",
"root","root");
connection.setAutoCommit(false);  
PreparedStatement ps = connection.prepareStatement(  
  "insert into tb_user (name) values(?)");  
for (int i = 0; i < stuNum; i++) {  
  ps.setString(1,name);  
  ps.addBatch();  
}  
ps.executeBatch();  
connection.commit();  
connection.close();

@Select Anotasyonu
Şöyle yaparız.
@Select("select from courses where id = #{id}")
public Course getById(int id);

Hiç yorum yok:

Yorum Gönder