第一步妥泉,引用Maven依賴:
<dependency>
<groupId>com.github.braisdom</groupId>
<artifactId>objective-sql</artifactId>
<version>1.3.4</version>
</dependency>
第二步,使用Annotation 定義一個(gè)DomainModel :
import com.github.braisdom.objsql.annotations.Column;
import com.github.braisdom.objsql.annotations.DomainModel;
import com.github.braisdom.objsql.annotations.Queryable;
import com.github.braisdom.objsql.annotations.Relation;
import com.github.braisdom.objsql.relation.RelationType;
import java.util.List;
@DomainModel
public class Member {
@Queryable
@Column(updatable = false)
private String no;
@Queryable
private String name;
private Integer gender;
private String mobile;
private String otherInfo;
@Relation(relationType = RelationType.HAS_MANY)
private List<Order> orders;
}
第三步:定義ConnectionFactory 并注入ObjectiveSQL:
class MySQLConnectionFactory implements ConnectionFactory {
@Override
public Connection getConnection(String dataSourceName) throws SQLException {
String url = "jdbc:mysql://localhost:4406/objective_sql?serverTimezone=Asia/Shanghai";
String user = "root";
String password = "123456";
Connection connection;
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(url, user, password);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
throw new IllegalStateException(ex.getMessage(), ex);
}
return connection;
}
}
Databases.installConnectionFactory(new MySQLConnectionFactory());
第四步:執(zhí)行數(shù)據(jù)庫操作
- 創(chuàng)建會(huì)員
Member newMember = new Member();
newMember.setNo("100000")
.setName("Pamela")
.setGender(1)
.setRegisteredAtWithJoda(DateTime.now())
.setUpdatedAt(Timestamp.valueOf("2020-10-05 00:00:00"))
.setMobile("15011112222");
Member member = Member.create(newMember, true);
INSERT INTO `members` (`no`,`name`,`gender`,`mobile`,`extended_attributes`,`registered_at`,`updated_at`)
VALUES (?,?,?,?,?,?,?), with: [100000,Pamela,1,15011112222,null,2020-10-08 11:01:57.368,2020-10-05 00:00:00.0]
- 統(tǒng)計(jì)會(huì)員數(shù)量
long count = Member.count("id > ?", 10);
SELECT COUNT(*) AS count_rows FROM `members`
更多請(qǐng)?jiān)L問:https://github.com/braisdom/ObjectiveSql