在clojure中使用korma在mysql中插入多行
我正在开发一个restful应用程序,它在后面使用Clojure,在前面使用Angular。我有以下表格:客户、订单、项目、订单项目。我使用korma与MySql数据库通信。当我为所有实体进行CRUD操作时,一切都正常。但我不知道如何在数据库中插入多行?我应该在korma中使用事务吗在clojure中使用korma在mysql中插入多行,mysql,clojure,crud,compojure,korma,Mysql,Clojure,Crud,Compojure,Korma,我正在开发一个restful应用程序,它在后面使用Clojure,在前面使用Angular。我有以下表格:客户、订单、项目、订单项目。我使用korma与MySql数据库通信。当我为所有实体进行CRUD操作时,一切都正常。但我不知道如何在数据库中插入多行?我应该在korma中使用事务吗 (declare customer) (declare customerorder) (declare item) (declare orderitems) (schema/defschema OrderItem
(declare customer)
(declare customerorder)
(declare item)
(declare orderitems)
(schema/defschema OrderItem
{
:OrderItemId schema/Int
:OrderId schema/Int
:ItemId schema/Int
:Quantity schema/Int
})
(schema/defschema Customer
{
:CustomerId schema/Int
:Name schema/Str
:Contact schema/Str
})
(schema/defschema UpdateCustomer
{
:Name schema/Str
:Contact schema/Str
})
(schema/defschema NewCustomer
{
:Name schema/Str
:Contact schema/Str
})
(schema/defschema Order
{
:OrderId schema/Int
:CustomerId schema/Int
:PMethod schema/Str
:GTotal schema/Num
})
(schema/defschema Item
{
:ItemId schema/Int
:Name schema/Str
:Price schema/Num
})
(defentity customer
(pk :CustomerId)
(has-many customerorder {:fk :CustomerId})
(entity-fields :CustomerId :Name :Contact))
(defentity customerorder
(pk :OrderId)
(has-many orderitems {:fk :OrderId})
(belongs-to customer {:fk :CustomerId})
(entity-fields :PMethod :GTotal :OrderId)
)
(defentity item
(pk :ItemId)
(entity-fields :ItemId :Name :Price)
(has-many orderitems {:fk :ItemId}))
(defentity orderitems
(pk :OrderItemId)
(belongs-to item {:fk :ItemId})
(belongs-to customerorder {:fk :OrderId})
(entity-fields :OrderItemId :ItemId :Quantity))
下面是我的查询,用于选择使用现金支付订单和订单项目的客户:
(defn get-customersbypmethod [PMethod]
(select customerorder (with customer (with orderitems)) (where {:PMethod PMethod})))
我的问题是如何插入带有订单项目的订单?Korma文档说明如下: 插入查询使用函数(值)添加记录。它接受单个映射或映射集合,并返回第一条插入记录的id
;; You can insert a single value:
(insert users
(values {:first "john" :last "doe"}))
;; or a collection of several:
(insert users
(values [{:first "john" :last "doe"}
{:first "jane" :last "doe"}]))
;; You can also compose inserts:
(def base (-> (insert* users)
(values {:first "john" :last "doe"})))
(-> base
(values {:first "jane" :last "doe"})
(insert))
;; Same thing as the collection insert
只需使用(transaction)宏即可在Korma中执行事务,该宏确保在其中执行的所有查询都是单个事务的一部分。然后,如果需要,可以使用(回滚)函数强制事务回滚
(transaction
(insert users
(values {:first "cool"}))
(insert address
(values {:address1 "cool"})))
(transaction
(if-not (valid?)
(rollback)
(do-complicated-query))
(when-not (is-rollback?)
(println "success!")))
希望这有帮助。Korma是一个稳定且文档齐全的库。我无法回答您的问题,但作为Korma使用的org.clojure/java.jdbc的维护者,我想指出a)Korma已经好几年没有更新了(0.4.3是四年半前发布的)b)Korma的使用并不广泛,因此获得支持可能很困难;c)它使用了非常旧的clojure.java.jdbc版本,该版本也不再维护(鼓励用户迁移到next.jdbc)。ORM样式库在Clojure中并不常见,但如果您真的想要这种样式,请查看Toucan,它至少仍在维护中。