Insert a POJO INTO MariaDB using JDBC

kotlin · · 48 次点击    
<p>I am currently in a pickle as I am not sure if I missed something. However, I am having trouble figuring out how to insert a POJO obtained from Retrofit2 into my MariaDB interface using jdbc. I have taken to manually converting all my objects into KV pairs before I insert. Is there a proper way to do this? Or a Kotlin specific method to doing this?</p> <hr/>**评论:**<br/><br/>Apfelmann: <pre><p>I would suggest using a JPA Implementation like Hibernate, or some other ORM like Requery.</p> <p>If you are going with Hibernate here is a nice tutorial I followed <a href="https://hashnode.com/post/how-i-built-my-first-kotlin-vertx-hibernate-stack-cixhsnv1b002au6539uu6iw7r" rel="nofollow">https://hashnode.com/post/how-i-built-my-first-kotlin-vertx-hibernate-stack-cixhsnv1b002au6539uu6iw7r</a> also use the kotlin-jpa pluging</p></pre>pmmeforotterfacts: <pre><p>Thank you! I guess I should have looked at ORMs (for some reason I assumed jdbc was an ORM)</p></pre>kevinherron: <pre><p>The common solution is to come up with some <strong>mapping</strong> of your <strong>objects</strong> to the <strong>relational</strong> nature of database tables.</p> <p>Most would use some kind of ORM for this rather than roll their own.</p></pre>pmmeforotterfacts: <pre><p>Thank you!</p></pre>bah_si_en_fait: <pre><p>One excellent option if you do not intend to go the full Hibernate way, I would recommend <a href="http://jdbi.org/" rel="nofollow">Jdbi</a>. It&#39;s a lightweight interface sitting on top of JDBC, amazingly easy to use, and integrates pretty damn well with Kotlin. </p> <p>As an example, assuming you wanted to insert a <code>Person</code> object into a table, without wanting to make said object a model of your database, you could go about it this way:</p> <pre><code>interface PersonInsertions { @SqlUpdate(&#34;&#34;&#34; INSERT INTO person (name, age, awesomeness, type) VALUES (:person.name, :person.age, :person.awesome, :type) &#34;&#34;&#34; fun insertAwesomePerson(@BindBean(&#34;person&#34;) person: Person, type: Int) fun insertAwesomeClient(person: Person) = insertAwesomePerson(person, PersonType.Client) ... } </code></pre> <p>It has automatic mapping of simple objects (no nested objects), and mapping said nested objects if you need it is relatively simple (it is mostly a matter of implementing a mapper for this type of object, and letting the default mapper do its work on each independent object. So, a Person holding an Address object could be mapped by reading the person without the address into an object, then reading that address into the person. Two lines, plus the inevitable override boilerplate)</p></pre>
48 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet