Step 2 of partner4java p4jorm: Use of jdbc

Source: Internet
Author: User

Traditional JDBC: When you add, delete, modify, and query data, do you want to spell SQL statements? It's hard to spell out, get results, and traverse encapsulation. It's crazy to encounter a table with hundreds of fields left over. P4jorm: When p4jorm is used, the normal CURD, that is, the CURD that occupies most of our work, does not need to be written (actually a row does not need to be written ); when querying the front-end, we only need to put the corresponding data into formbean (if you use a framework such as struts, formbean Data encapsulation does not need to be done by yourself ); you don't have to worry about more fields. You don't forget to close the database connection and get the boss k. Next we will enter the thirty-minute learning time: (this will be presented in MySQL databases. Currently, only MySQL is supported. If you need to support other databases, please email us and try to add them) first, create a web project. If you use maven, put the maven directory of the compressed package into your local machine (because it is not released to the public server ), add maven dependency [java] <dependency> <groupId> partner4java </groupId> <artifactId> p4jorm </artifactId> <version> 1.0.0 </version> <exclusions> <exclusion> <groupId> org. hibernate </groupId> <artifactId> hibernate-core </artifactId> </exclusion> </exclusions> </dependency> [html] If maven is not used, The architecture of jar for the p4jorm-1.0.0.jar, but also need to rely on other jar, you can directly test all the jar helloworld Project (p4jorm_jdbc_test \ WebRoot \ WEB-INF \ lib. Step 1: Create a table as usual. Here we CREATE a user TABLE [SQL] CREATE TABLE 'user' ('id' int (11) NOT NULL AUTO_INCREMENT, 'username' varchar (20) NOT NULL, 'Password' varchar (20) not null, 'address' varchar (20) default null, primary key ('id') ENGINE = InnoDB AUTO_INCREMENT = 2 default charset = utf8; step 2: Create an object corresponding to a table. In other words, we need to create an object that carries table data. (Do you always have a place to store the data you have extracted from the database? Dear User, we are object-oriented.) [java] public class User implements Serializable {private static final long serialVersionUID =-8804762279661495240L; private int id; private String username; private String password; private String address ;... you can also use tools to automatically generate entities through the created tables and view the article http://blog.csdn.net/partner4java/article/details/8560289 in detail (we do not need annotations such as JPA here, you need to delete after generation) Step 3: add object annotation because I need to identify and analyze objects. Here you generally only need to add two annotations P4jEntity to mark objects on the class, P4 The jId is marked on the corresponding primary key field (for more information about the annotations, see the appendix doc/index.html. We will not talk about the "please refer to the document" or other phone calls later, you can go to the document immediately. If the explanation in the document is unclear, please email me) [java] @ P4jEntity public class User implements Serializable {private static final long serialVersionUID =-8804762279661495240L; @ P4jId private int id; private String username; private String password; private String address; we have said that p4jorm only needs two annotations to work together, now you can add, delete, modify, and query the user table. Step 4: organize the test environment and write the test case environment: As mentioned in the first step, the current version of p4jorm requires spring. If you are not familiar with spring ioc, refer to the article http://blog.csdn.net/partner4java/article/details/8194747 if the current spring is not in your learning scope, do not worry, you just need to put the configuration file I provided into the corresponding directory to p4jorm_jdbc_test \ src \ main \ resources there are three files: datasource-c3p0.xml, beans. xml jdbc-c3p0.properties: you only need to care about this, where your database connection information is configured (because we use c3p0 here, then the corresponding jar also needs to be added) unit test: we currently use the first tool class-p4jdbcdaotemplate [java] public class Us ErTest {private P4jJdbcDaoTemplate daoTemplate; // The setUp method is actually to create a p4jdbcdaotemplate for us. For details, refer to the P4jJdbcDaoTemplate description in the document @ Before public void setUp () throws Exception {// here the ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("/META-INF/spring/beans is created for the spring container. xml "); // you have created a daoTemplate and passed in namedParameterJdbcTemplate daoTemplate = new P4jJdbcDaoTemplate (applicationContext. getBea N ("namedParameterJdbcTemplate", NamedParameterJdbcTemplate. class);} // we perform the first save Test @ Test public void testSave () {for (int I = 0; I <1000; I ++) {// create a user entity and enter User user User = new user (); user. setPassword ("123456" + I); user. setUsername ("partner4java" + I); user. setAddress ("partner4java@163.com"); // we only need this sentence to save the user into the database daoTemplate. save (user) ;}} one thousand items are saved. When you see the new data in the data table, do you secretly like [java] // The updated data must be noted that we only update the data of the specified id without updating the data with a null value. You can leave the null character @ Test public void testUpdate () {User user = new User (); user. setPassword (""); user. setUsername ("world"); // sets the id, which indicates the user of the data to be updated. setId (1); daoTemplate. update (user) ;}@ Test public void testDelete () {daoTemplate. delete (User. class, 1);} update and delete are also so simple. There are two Annotations about entities: p4jTransient is used to specify that the field is irrelevant to the database, and P4jColumn is used to specify the ing of the field (because we correspond to the database field name based on the name of the object member field, if the two are different, ). Query data: After you click "form" to submit a query, do you think that I have already given you the data? Why don't you automatically return the data I want? Why do I need to spell and query SQL statements? Well, I will help you implement it, and I don't want to work too much for you: if you use a struts-like framework, you must have a layer called formbean, you only need to add annotations to several fields that need to participate in the query in formbean (it takes a few seconds for you ). (First of all, let's take a look at the data encapsulation that form submits to formbean. This is the work of the MVC framework and I will not help you with it.) We didn't use the MVC framework here, but directly used Servlet: com. partner4java. jdbctest. web. userListServlet (this is not our focus and we will not post it, so we can see the attachment by ourselves) we have defined formbean: [java]/*** you will find that it is very similar to my User class, in general, formbean is much less than entity, or has more time fields, which is not our focus here, not much will be explained. ** @ author partner4java **/public class UserFormBean implements Serializable {private static final long serialVersionUID = 4358513464951563450L; priv Ate String username; private String password; private String address; with formbean, we still add two Annotations: P4jQueryForm (marked on the class, indicating that the field assignment of this class will be used to query spelling, this annotation must be specified), P4jGeneral (used to declare a field as a common query, such as an equivalent query), and P4jLike (used to declare a field as a like fuzzy query ), for details, refer to the appendix document [java] @ P4jQueryForm public class UserFormBean implements Serializable {private static final long serialVersionUID = finished; // indicates that we will find the data named @ P4jGeneral (generalQueryType = GeneralQuer YType. EQ) private String username; // I do not have any annotations and will not participate in the query of private String password; // INDICATES THAT WE WILL fuzzy query @ P4jLike private String address based on the address; without writing any dao or service, we can directly complete the display layer: [java]/***. Here is a simple example. Servlet is directly used, if you use the MVC Framework, UserFormbean is automatically obtained ** @ author partner4java **/public class UserListServlet extends HttpServlet {private static final long serialVersionUID =-5372697351493999670L; @ Override protected v Oid service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {UserFormBean formBean = getUserForm (request); String currentPage = getCurrentPage (request ); // here you only need the type to be returned, formbean, the current page, and the return type is not used even for forced conversion, but is it not necessary? PageData <User> users = p4jdbcdaotemplatesingleton. getJdbcDaoTemplate (). query (User. class, formBean, new PageIndex (new Integer (currentPage), null); request. setAttribute ("users", users); request. getRequestDispatcher ("/WEB-INF/page/users. jsp ");} like a common interface, jsp encapsulates a page: [html] <input type = "hidden" name = "currentPage" value = "$ {pageData. pageIndex. currentPage} "/> <div class =" pager "> <c: if test =" $ {page Data. pageIndex. currentPage> 1} "> <a class =" prv "href =" javascript: topage ('$ {pageData. pageIndex. currentPage-1} ') "> <span> previous page </span> </a> </c: if> <c: forEach begin =" $ {pageData. pageIndex. startPage} "end =" $ {pageData. pageIndex. endPage} "varStatus =" varStatus "> <c: if test =" $ {pageData. pageIndex. currentPage = (pageData. pageIndex. startPage + varStatus. count-1)} "> <strong> <span >$ {pageData. pageIndex. st ArtPage + varStatus. count-1 }</span> </strong> </c: if> <c: if test = "$ {pageData. pageIndex. currentPage! = (PageData. pageIndex. startPage + varStatus. count-1)} "> <a href =" javascript: topage ('$ {pageData. pageIndex. startPage + varStatus. count-1} ') "> <span >$ {pageData. pageIndex. startPage + varStatus. count-1} </span> </a> </c: if> </c: forEach> <c: if test = "$ {pageData. pageIndex. currentPage <pageData. totalCount/pageData. pageIndex. maxResult} "> <a class =" next "href =" javascript: topage ('$ {pageData. pageIndex. c UrrentPage + 1} ') "> <span> next page </span> </a> </c: if> </div> is easy to use. For jsp, we only need to complete. jsp: [html] <form action = "userlist" method = "post"> User Name: <input type = "text" name = "username" value = "$ {username}"/> <br/> address: <input type = "text" name = "address" value = "$ {address}"/> <input type = "submit" value = "query"/> <br/> <c: forEach items = "$ {pageData. resultlist} "var =" user ">$ {user. username} -- $ {user. password} -- $ {user. address} <br/> </c: forEach> <% @ include file = "fenye. jsp "%> </Form> so far, we have completed the CURD operation. Let's look back at what you need to do? Entity two annotations, formbean three annotations. Everything else is unavoidable. If the above generic CURD cannot meet your needs, you can use P4jJpaDaoSupport to define an interface: [java] public interface UserDao extends P4jDao <User >{} [java] public class UserDaoImpl extends P4jJdbcDaoSupport <User> implements UserDao {} [java] If you need additional methods, complete this in your own UserDao interface and implement it in the UserDaoImpl class. (Through inheritance, you will find that when you continue the CURD operation, you can omit the object type, because the parent class requires the object type to be passed in during inheritance) one thing to note is that our p4jdbcdaosupport requires NamedParameterJdbcTemplate resources. You can manually insert them like our p4jdbcdaotemplate. However, we recommend that you use Spring IoC to hand over your UserDaoImpl to Spring and plug it in automatically.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.