preface
Here I will adopt mybatis3.2 Make database persistent , Many of them may stay under the guidance of their teachers , Still stuck with traditional JDBC Persistent access data layer . today , Let's talk about interface oriented programming and how to take advantage of annotations !
realization DAO Persistent layer
From the current Java Frame trend ,spring Framework still dominates , No matter what you use SSH Framework and SSM Framework development , Must be thorough spring There's nothing wrong with it .
From the current distribution of Internet companies , Small and medium-sized companies still own half of the country , They don't have a lot of money and development resources , In other words, very few companies use it hibernate+struts Development project , For small and medium-sized companies, the development of super large projects is beyond their consideration . that ,mybatis+springmvc Development framework is rising …
End of chat , Let me talk about the principle first :
use mybatis Define interface complete sql Statement mapping , The interface can also be directly used as DAO Use of components of .
Bridge mode, you know ?
Application of bridge mode here :
Using this pattern can embody business logic component encapsulation DAO Patterns of components , You can also separate business logic components from DAO Functions of components . in other words , Business logic components are responsible for changes in business logic , and DAO Components are responsible for persistent changes .
Benefits of doing so :
① each DAO Component contains the access logic of the database .
② each DAO Component can complete basic CRUD Etc .
1. Common constant class
HrmConstants class
1234567891011121314151617181920212223/** * * constant * */public class HrmConstants
{ // Database table constant public static final String USERTABLE="user_inf"; public
static final String DEPTTABLE="dept_inf"; public static final String
JOBTABLE="job_inf"; public static final String EMPLOYEETABLE="employee_inf";
public static final String NOTICETABLE="notice_inf"; public static final
String DOCUMENTTABLE="document_inf"; // Sign in public static final String
LOGIN="loginFrom"; // User's session object public static final String USER_SESSION=
"user_session"; // Default per page 4 Data public static int PAGE_DEFAULT_SIZE=4; }
I won't post the database here . This common constant class is defined according to the structure of the database table , That is to say, in the database, I created 6 Tables , Each table corresponds to this class one by one . As for here session object , It is for the later stage of writing control layer , Nothing to do with what I've said .
2. Entity class
1234567891011121314151617181920212223242526272829303132333435363738394041424344
4546474849505152535455565758596061626364656667/** * * User entity class * */public class
User { private Integer id;//id private String username;// user name private
String loginname;// Login name private String password;// password private Integer
status;// state private Date createDate;// created date public User() { }
//setter and getter method public Integer getId() { return id; } public
void setId(Integer id) { this.id = id; } public String
getUsername() { return username; } public void setUsername(String
username) { this.username = username; } public String
getLoginname() { return loginname; } public void
setLoginname(String loginname) { this.loginname = loginname; }
public String getPassword() { return password; } public void
setPassword(String password) { this.password = password; } public
Integer getStatus() { return status; } public void
setStatus(Integer status) { this.status = status; } public Date
getCreateDate() { return createDate; } public void
setCreateDate(Date createDate) { this.createDate = createDate; } }
here , I will make a case introduction with user entity class . The basic principle of entity class is to follow javabean rule , That is to say, public class , Private member variable and its own construction method without parameter . of course , I used it here setter and getter The method simply encapsulates it .
3. definition DAO Interface
123456789101112131415161718192021222324252627282930313233343536373839/** * *
UserDao Interface implementation class of * */public interface UserDao { // Login user name and password query employee @Select(
"select * from "+USERTABLE+" where loginname = #{loginname} and password =
#{password} ") User selectByLoginnmameAndPassword( @Param(
"loginname") String loginname, @Param("password") String password
); // according to Id Query users @Select("select * from "+USERTABLE+" where
id = #{id} ") User selectById(Integer id); // according to Id delete user @Delete(
"delete from "+USERTABLE+" where id = #{id} ") void deleteById(Integer id);
// Dynamically modify users @SelectProvider(method = "updateUser", type =
UserDynaSqlProvider.class) void update(User user); // Dynamic query
@SelectProvider(method = "selectWhitParam", type = UserDynaSqlProvider.class)
List<User> selectByPage(Map<String, Object> params); // Total number of users queried by parameters
@SelectProvider(method = "count", type = UserDynaSqlProvider.class)
Integer count(Map<String, Object> params); // Insert users dynamically @SelectProvider
(method ="inserUser", type = UserDynaSqlProvider.class) void save(User user);
}
This is the real beginning of sublimation , First of all, I've only defined one UserDao Interface of , And then make the most of it mybatis Annotation advantage of , Defined ’ Login user name and password query employee ’ Method of ……
Here, I'd like to add some explanatory knowledge for you :
@Select annotation , Don't explain that , It is equivalent to an annotation for storing query statements , Defined on a method , The effect is equivalent to writing a query statement in the configuration file .
@Param annotation , It's an explanation of the parameters . Used here string
loginname It is defined in the public constant class . How to put it? , We can understand that request.setAttribute(“”,”") The sublimation of this form .
@SelectProvider annotation , For generating queries sql sentence , Different from @Select annotation . Structurally ,@SelectProvide Specified a Class And methods , By calling Class This method on to get sql sentence .
matters needing attention :
① there @Param Annotations are based on mybatis Framed , no spring On frame , Pay attention when importing packages !
②@SelectProvider Annotation has a span in the thinking of programming , Because it needs a class And its methods , So when defining this annotation , Be sure to think about what the classes and methods in the next hierarchy need to do ! of course , Methods in interfaces , It can be budgeted in advance , But the note on it , You have to think more to make a decision !
③ Common constant class . On the application of this interface , Since it's interface oriented programming , And complete the basic operation of the database , Then it must be imported into the public constant class USERTABLE Of .
④id = #{id} Generated sql Statement is id = ?
4. dynamic SQL Provider class
1234567891011121314151617181920212223242526272829303132333435363738394041424344
45464748495051525354555657585960616263646566676869707172737475767778798081828384
858687888990public class UserDynaSqlProvider { // Paging dynamic query public String
selectWhitParam(final Map<String, Object> params) { String sql=new SQL(){
{ SELECT("*"); FROM(USERTABLE);
if (params.get("user")!=null) { User
user=(User) params.get("user"); if (user.getUsername()!=null
&& !user.getUsername().equals("")) { WHERE(" username
LIKE CONCAT('%',#{user.username},'%') "); }
if (user.getStatus()!=null && !user.getStatus().equals(""))
{ WHERE(" status LIKE CONCAT('%',#{user.status},'%') ");
} } } }.toString();
if (params.get("pageModel")!=null) { sql += " limit
#{pageModel.firstLimitParam} , #{pageModel.pageSize} "; } return
sql; } // Total number of dynamic queries public String count(final Map<String, Object>
params) { return new SQL(){ { SELECT("*");
FROM(USERTABLE); if (params.get("user") !=null) {
User user=(User) params.get("user"); if
(user.getUsername()!=null && !user.getUsername().equals("")) {
WHERE(" username LIKE CONCAT('%',#{user.username},'%') "
); } if (user.getStatus()!=null &&
!user.getStatus().equals("")) { WHERE(" status LIKE
CONCAT('%',#{user.status},'%') "); } }
} }.toString(); } // Dynamic insertion public String
inserUser(final User user) { return new SQL(){ {
INSERT_INTO(USERTABLE); if (user.getUsername()!=
null && !user.getUsername().equals("")) { VALUES("username",
"#{username}"); } if (user.getStatus()!=null &&
!user.getStatus().equals("")) { VALUES("status", "#{status}"
); } if (user.getLoginname()!=null &&
!user.getLoginname().equals("")) { VALUES("loginname",
"#{loginname}"); } if (user.getPassword()!=null
&& !user.getPassword().equals("")) { VALUES("password",
"#{password}"); } } }.toString(); }
// Dynamic update public String updateUser(final User user) { return new SQL(){
{ UPDATE(USERTABLE); if
(user.getUsername()!=null) { SET(" username = #{username} ");
} if (user.getLoginname()!=null) {
SET(" loginname = #{loginname} "); }
if (user.getPassword()!=null) { SET("
password = #{password} "); } if
(user.getStatus()!=null) { SET(" status = #{status} ");
} if (user.getCreateDate()!=null) {
SET(" create_date = #{createDate} "); }
WHERE(" id = #{id} "); } }.toString(); }}
As I said earlier when I wrote the interface class , Now that it's used @SelectProvider annotation , It's bound to use one class And its methods . We used it four times in the interface class @SelectProvider annotation , So there are four ways to do it , Paging dynamic query (selectWhitParam), Total number of dynamic queries (count), Dynamic insertion (inserUser), Dynamic update (updateUser).
This class is specially provided for the interface sql Statement serving , No longer need to implement traditional interfaces , Using annotations instead of the original tedious things .
ps: Maybe someone will wonder , How do we configure what we write in applicationContext.xml Inside ? Will it be very troublesome ? Now? , I tell you , No trouble at all !
configuration file
applicationContext.xml
12345678<!-- mybatis:scan Can scan com.dao.inter All interfaces under the package are treated as spring Of bean to configure , Dependency injection can be done later
--> <mybatis:scan base-package="com.dao.inter"/> <!--
use PropertyOverrideConfigurer Post processor load data source parameters --> <context:property-override
location="classpath:db.properties" /> <!-- to configure c3p0 data source --> <bean id=
"dataSource" class="com.mchange.v2.c3p0.CombopooledDataSource "/> <!--
to configure sqlSessionFactory.org.mybatis.spring.SqlSessionFactoryBean yes mybatis Community development for integration Spring Of bean
--> <bean id="sqlSessionFactory" class=
"org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource"/>
db.properties
12345678dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/hrm_dbdataSource.user=root
dataSource.password=rootdataSource.maxPoolSize=20dataSource.maxIdleTime=1000
dataSource.minPoolSize=6dataSource.initialPoolSize=5
principle :mybatis Persistence of DAO Interface only needs to pass SqlSession Of getMapper Method to obtain the corresponding interface instance , So as to call the interface method to complete the operation of the database , And in spring In the container , Only responsible for generation and management DAO Components of .
I'm done ? So do you think it's better than traditional JDBC Persistent access is easier ? I think , At least it's more convenient .
If you want to IT High salary in the industry , Can attend our training camp course , Choose the best course for yourself , Teach by yourself ,7 Months later , Enter famous enterprises and get high salary . Our courses include :Java Engineering , High performance and distributed , High performance , explain profound theories in simple language . Elevated structure . performance tuning ,Spring,MyBatis,Netty Source code analysis and big data . If you want to get paid , Want to learn , Want a good job , Want to compete with others to gain an advantage , I want to interview with ALI, but I'm afraid I can't , You can come , Group number is :
650385180
notes : Additive group requirements
1, have 1-5 Experienced , I don't know where to start in the face of the current popular technology , Those who need to break through the technical bottleneck can be added .
2, I've been in the company for a long time , It's very easy , But I met a wall in my job interview . Need to study in a short time , If you change jobs and get a high salary, you can add .
3, If you don't have work experience , But the foundation is very solid , Yes java Working mechanism , Common design ideas , Common java Master the development framework skillfully , Can be added .
4, I think I'm good B, General needs can be met . But the knowledge is not systematic , It's hard to continue to break through in the field of technology .
5. Ali Java Advanced Daniel's live explanation knowledge points , Sharing knowledge , Combing and summarizing of many years' working experience , With all of you , Scientifically establish their own technical system and technical cognition !
6. Small size or small white and other groups are not given , thank you .
The goal is already there , Let's see the action ! remember : Learning is always your own business , You don't have much time , You learn sometimes, but you can use what you learn for more free time ! Time is an essential part of life , It is also the fundamental measure of the existence of all things , Where our time is, where our life is ! Where our values will rise or fall !Java programmer , Come on
Technology
Daily Recommendation