登录
推荐 文章 Go 技术 课程 下载 专题 AI
首页 >  数据库 >  MySQL

Java ORM ObjectiveSQL 之 MySQL 实战

来源:SegmentFault

时间:2023-01-11 10:32:39 418浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《Java ORM ObjectiveSQL 之 MySQL 实战》,聊聊MySQL、Java、ORM、springboot,我们一起来看看吧!

第一步,引用Maven依赖:

com.github.braisdomobjective-sql1.3.4

第二步,使用Annotation 定义一个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 orders;

}

第三步:定义ConnectionFactory 并注入ObjectiveSQL:

private static 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());

第四步:执行数据库操作
1) 创建会员

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]

2) 统计会员数量

long count = Member.count("id > ?", 10);

SELECT COUNT(*) AS count_rows FROM `members`

更多请访问:https://github.com/braisdom/ObjectiveSql

本篇关于《Java ORM ObjectiveSQL 之 MySQL 实战》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于数据库的相关知识,请关注golang学习网公众号!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表