mybatis是一個連資料庫的框架
寫起來很簡明, 算是一種主流框架之一
以下就介紹整合的方法
1. 官網http://www.mybatis.org/mybatis-3/
2. 首先在MySQL的DB建立一個table裡面有欄位
3. 接著在Gradle內加入
compile 'org.mybatis:mybatis:3.3.0'
compile 'org.mybatis:mybatis-spring:1.2.3'
4. 然後在專案中建立一個mapper, 和一個對映table欄位的module
5. 接著在mapper內建立一個interface, 然後在anotation中加入SQL語句
範例如下:
public interface ExampleMapper {
@Insert("INSERT into example(Field1, Field2) VALUES(#{field1}, #{field2})")
void insert(Example example);
}
6. Module則是最基本的型態, 但是要對應table
public class Example {
private int Field1;
private String Field2;
public int getField1() {
return Field1;
}
public void setField1(int field1) {
Field1 = field1;
}
public String getField2() {
return Field2;
}
public void setField2(String field2) {
Field2 = field2;
}
}
7. 接著在xml內加入bean和scan的bean
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
和
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.rx.example.mybatis.mapper" />
</bean>
8. 在web.xml內加入剛剛的xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mybatis.xml</param-value>
</context-param>
9. 接著再要用的地方宣告mapper使用
@Autowired
private ExampleMapper mapper;
Example example = new Example();
example.setField1(1);
example.setField2("value1");
mapper.insert(example);
10. 最後就可以看到直接連動到DB了