• Stars
    star
    227
  • Rank 175,900 (Top 4 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created over 6 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Minimal database operation library.

Anima

Anima allows you to query database like SQL and Stream. a simple DSL syntax, supports multiple databases, integrates well with Java8, supports multiple relational mappings, and is a database manipulation tool.

Document

Travis Build Codacy Badge codecov License Twitter URL

Feature

  • Simple DSL
  • H2、MySQL、SQLite、PostgreSQL、Oracle、SqlServer
  • Paging support
  • Flexible configuration
  • Connection pool support
  • Support LocalDateLocalDateTime
  • Support lambda expression
  • Relationship (hasOnehasManybelongsTo)
  • SQL performance statistics
  • Based Java8

Usage

Latest snapshot version

If you want to prioritize new features or some BUG fixes you can use it, you need to specify the snapshot repository in pom.xml

<repository>
    <id>snapshots-repo</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    <releases>
        <enabled>false</enabled>
    </releases>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>

<dependency>
    <groupId>com.hellokaton</groupId>
    <artifactId>anima</artifactId>
    <version>0.3.1</version>
</dependency>

Here's the RELEASE version.

As Gradle

compile 'com.hellokaton:anima:0.3.1'

As Maven

<dependency>
    <groupId>com.hellokaton</groupId>
    <artifactId>anima</artifactId>
    <version>0.3.1</version>
</dependency>

📒 Although Anima can also be used by adding a jar package, we do not recommend doing this.

Examples

Open Connection

// MySQL
Anima.open("jdbc:mysql://127.0.0.1:3306/demo", "root", "123456");

// SQLite
Anima.open("jdbc:sqlite:./demo.db");

// H2
Anima.open("jdbc:h2:file:~/demo;FILE_LOCK=FS;PAGE_SIZE=1024;CACHE_SIZE=8192", "sa", "");

// DataSource
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(blade.environment().getOrNull("jdbc.url"));
dataSource.setUsername(blade.environment().getOrNull("jdbc.username"));
dataSource.setPassword(blade.environment().getOrNull("jdbc.password"));
Anima.open(dataSource);

📕 This operation only needs one time

public class User extends Model {
    
    private Integer id;
    private String  userName;
    private Integer age;
    
    public User() {
    }
    
    public User(String userName, Integer age) {
        this.userName = userName;
        this.age = age;
    }
    
}

Table Structure

CREATE TABLE `users` (
  `id` IDENTITY PRIMARY KEY,
  `user_name` varchar(50) NOT NULL,
  `age` int(11)
)

Query

long count = select().from(User.class).count();
// SELECT COUNT(*) FROM users

long count = select().from(User.class).where("age > ?", 15).isNotNull("user_name").count();
// SELECT COUNT(*) FROM users WHERE age > ? AND user_name IS NOT NULL

User user = select().from(User.class).byId(2);
// SELECT * FROM users WHERE id = ?

List<User> users = select().from(User.class).byIds(1, 2, 3);
// SELECT * FROM users WHERE id IN (?, ?, ?)

String name = select().bySQL(String.class, "select user_name from users limit 1").one();

List<String> names = select().bySQL(String.class, "select user_name from users limit ?", 3);

List<User> users = select().from(User.class).all();
// SELECT * FROM users

List<User> users = select().from(User.class).like("user_name", "%o%").all();
// SELECT * FROM users WHERE user_name LIKE ?

Limit

List<User> users = select().from(User.class).order("id desc").limit(5);
// SELECT * FROM users ORDER BY id desc

Paging

Page<User> userPage = select().from(User.class).order("id desc").page(1, 3);
// SELECT * FROM users ORDER BY id desc LIMIT ?, ?

Map

select().from(User.class).map(User::getUserName).limit(3).collect(Collectors.toList());

Filter

select().from(User.class).filter(u -> u.getAge() > 10).collect(Collectors.toList());

Lambda

User user = select().from(User.class).where(User::getUserName).eq("jack").one();
// SELECT * FROM users WHERE user_name = ?
List<User> user = select().from(User.class)
                .where(User::getUserName).notNull()
                .and(User::getAge).gt(10)
                .all();
// SELECT * FROM users WHERE user_name IS NOT NULL AND age > ?
select().from(User.class).order(User::getId, OrderBy.DESC).order(User::getAge, OrderBy.ASC).all();
// SELECT * FROM users ORDER BY  id DESC, age ASC

Join

@Table(name = "order_info")
@Data
public class OrderInfo extends Model {

    private Long id;

    private Integer uid;

    @Column(name = "productname")
    private String productName;

    private LocalDateTime createTime;

    @Ignore
    private User user;
    
    @Ignore
    private Address address;

}
// HasOne
OrderInfo orderInfo = select().from(OrderInfo.class)
        .join(
            Joins.with(Address.class).as(OrderInfo::getAddress)
                 .on(OrderInfo::getId, Address::getOrderId)
        ).byId(3);

orderInfo = select().from(OrderInfo.class)
        .join(
            Joins.with(Address.class).as(OrderInfo::getAddress)
                 .on(OrderInfo::getId, Address::getOrderId)
        )
        .join(
                Joins.with(User.class).as(OrderInfo::getUser)
                        .on(OrderInfo::getUid, User::getId)
        ).byId(3);

// ManyToOne
orderInfo = select().from(OrderInfo.class)
        .join(
            Joins.with(User.class).as(OrderInfo::getUser)
                 .on(OrderInfo::getUid, User::getId)
        ).byId(3);

// OneToMany
UserDto userDto = select().from(UserDto.class).join(
            Joins.with(OrderInfo.class).as(UserDto::getOrders)
                 .on(UserDto::getId, OrderInfo::getUid)
        ).byId(1);

Insert

Integer id = new User("biezhi", 100).save().asInt();
// INSERT INTO users(id,user_name,age) VALUES (?,?,?)

or

Anima.save(new User("jack", 100));

Batch Save

List<User> users = new ArrayList<>();
users.add(new User("user1", 10));
users.add(new User("user2", 11));
users.add(new User("user3", 12));
Anima.saveBatch(users);

📘 This operation will begin a transaction and rollback when there is a transaction that is unsuccessful.

Update

int result  = update().from(User.class).set("user_name", newName).where("id", 1).execute();
// UPDATE users SET username = ? WHERE id = ?

or

int result = update().from(User.class).set("user_name", newName).where("id", 1).execute();
// UPDATE users SET user_name = ? WHERE id = ?

or

User user = new User();
user.setId(1);
user.setUserName("jack");
user.update();
// UPDATE users SET user_name = ? WHERE id = ?
update().from(User.class).set(User::getUserName, "base64").updateById(2);
update().from(User.class).set(User::getUserName, "base64").where(User::getId).eq(2).execute();

Delete

int result = delete().from(User.class).where("id", 1).execute();
// DELETE FROM users WHERE id = ?

or

User user = new User();
user.setAge(15);
user.setUserName("jack");
user.delete();
// DELETE FROM users WHERE user_name = ? and age = ?
delete().from(User.class).where(User::getId).deleteById(3);
delete().from(User.class).where(User::getId).eq(1).execute();
delete().from(User.class).where(User::getAge).lte(20).execute();

Transaction

Anima.atomic(() -> {
    int a = 1 / 0;
    new User("apple", 666).save();
}).catchException(e -> Assert.assertEquals(ArithmeticException.class, e.getClass()));

📗 Anima uses the atomic method to complete a transaction. normally, the code will not throw an exception. when a RuntimeException is caught, the transaction will be rollback.

Test Code

See here

License

Apache2

More Repositories

1

java-bible

🍌 我的技术摘要
HTML
2,984
star
2

30-seconds-of-java8

30 seconds to collect useful Java 8 snippet.
Java
2,368
star
3

wechat-api

🗯 wechat-api by java7.
Java
1,814
star
4

learn-java8

💖《跟上 Java 8》视频课程源码
Java
1,382
star
5

oh-my-email

📪 可能是最小的 Java 邮件发送库了,支持抄送、附件、模板等功能。
Java
711
star
6

profit

🤔 biezhi 在线打赏系统,开启你的要饭生涯。
Java
404
star
7

write-readable-code

🗾 编写可读代码的艺术代码仓库
Java
401
star
8

elves

🎊 Design and implement of lightweight crawler framework.
Java
317
star
9

java-library-examples

💪 example of common used libraries and frameworks, programming required, don't fork man.
Java
215
star
10

excel-plus

❇️ Improve the productivity of the Excel operation library. https://hellokaton.github.io/excel-plus/#/
Java
191
star
11

gorm-paginator

gorm pagination extension
Go
154
star
12

java-tips

🍓 Java 语言编程技巧、最佳实践
Java
149
star
13

gitmoji-plugin

Choose the right emoji emoticon for git commit, make git log commit more interesting.
Kotlin
112
star
14

java11-examples

java 11 example code
Java
98
star
15

telegram-bot-api

🤖 telegram bot api by java, help you quickly create a little robot.
Java
85
star
16

code-fonts

编程语言中流行的 8 款代码字体
PHP
63
star
17

lets-golang

《给 Java 程序员的 Go 私房菜》源码仓库
Go
62
star
18

oh-mybatis

🎈 A simple web app to generate mybatis code.
Java
60
star
19

terse

🍋 my typecho blog theme, Concise UI
CSS
59
star
20

hellokaton.com

✍️ https://hellokaton.com source code
HTML
46
star
21

webp-io

🌚 general format images and webp transform each other
Java
44
star
22

redis-dqueue

redis base delay queue
Java
44
star
23

oh-my-request

🔮 simple request library by java8
Java
43
star
24

oh-my-session

🍖 distributed session storage scheme, using redis to store data.
Java
42
star
25

swing-generate

🙊 Swing development code generator
Java
36
star
26

ss-panel

🐒 java shadowsocks panel(java版本shadowsocks面板)
HTML
34
star
27

industry-glossary

汇集行业英文术语,让你命名不在困难。
33
star
28

freechat

🐶 online anonymous chat application.
CSS
29
star
29

grice

🐜 A simple web document engine written by java.
CSS
29
star
30

goinx

💞 Multi-domain proxy by golang, fuck gfw proxy
Go
28
star
31

springmvc-plupload

🍃 Springmvc and servlet shard to upload demo
JavaScript
27
star
32

lowb

🤦🏻‍♂️ teach you to develop command-line source code using NodeJS
JavaScript
27
star
33

geekbb

😎 Geek dev club.
JavaScript
26
star
34

keeper

Java
25
star
35

mini-jq

🍣 mininal jquery, you don't need jquery!
JavaScript
21
star
36

spring-boot-examples

🕷 spring boot and spring cloud examples
Java
20
star
37

bye-2017

👋 Bye! my 2017
CSS
19
star
38

weather-cli

💊 weather command-line programs written in Golang.
Go
18
star
39

go-examples

🍄 learning golang code
Go
16
star
40

oh-my-jvm

☕️ using golang write jvm
Go
16
star
41

nice

🐹 使用blade开发的一款简洁的图片社交应用
Java
16
star
42

blog

blog source code
SCSS
16
star
43

learn-cute-netty

《可爱的Netty》源码仓库
Java
15
star
44

eve

👻 everyday explore, Github / HackNews / V2EX / Medium / Product Hunt.
Go
13
star
45

blade-cli

🐳 blade mvc cli application
Go
13
star
46

agon

🦉 my golang utilities, log json config and other
Go
12
star
47

wechat-api-examples

wechat-api examples, used java8.
Java
12
star
48

telegram-lottery

🤖 A telegram lottery bot that helps you achieve random rewards for group activities.
Go
11
star
49

java8-best-practices

java8 best practices source code.
Java
11
star
50

runcat_pyside

Python PySide6 of RunCat_for_windows
Python
10
star
51

dbkit

🚧 convenient implement of Database timing backup tool.
Go
10
star
52

lets-python

🍭 learning Python code
Python
9
star
53

java-2048

🎲 Java swing of 2048
Java
9
star
54

mapper-spring-boot-starter

通用mapper+pagehelper的spring boot starter
Java
9
star
55

blade-lattice

🔐 lightweight authentication and authorization, born for Blade.
Java
9
star
56

writty

🌝 A garbage writing platform, has given up.
Java
9
star
57

java-clojure-syntax-comparison

⚔️ Comparison of some code snippets in the Java and Clojure.
9
star
58

emojis

this is emoji images
8
star
59

ppocr-api

飞桨 OCR API Docker 镜像
Python
7
star
60

show-code

🌝 show github repositories card with html
JavaScript
7
star
61

probe

exploring the world beyond the wall, netty4 based proxy service.
Java
7
star
62

oh-my-monitor

🌈 C/S mode server monitoring (discontinuation of maintenance)
Java
6
star
63

moe

😛 simple cli spinner by golang.
Go
5
star
64

witty

🐝 witty is a smart golang robot
Go
5
star
65

gow

🙄 gow!!! a micro go web framework.
Go
5
star
66

primer-series

从入门到放弃系列衬衫生成器
CSS
5
star
67

spring-boot-starter-jetbrick

🐥 jetbrick-template的spring-boot starter
5
star
68

fastapi-tutorial

Here are some sample programs for me to learn fastapi.
Python
5
star
69

helidon-examples

💣 helidon framework example
Java
5
star
70

hellokaton

3
star
71

bar

🍺 static website builder written by golang
Go
3
star
72

tomato-clock

JavaScript
2
star
73

findor

🌟 let the world find you !
2
star
74

vite-react-mpa-example

React + Vite multi page application example
TypeScript
2
star
75

typecho-theme-modernist

a typecho theme modernist
PHP
2
star
76

homebrew-tap

Homebrew tap for biezhi/eve
Ruby
1
star
77

clojure-todo-list

The todo-list application that used clojure + ring
Clojure
1
star
78

juejun-alfred-workflow

a simple juejin alfred workflow example
Python
1
star