In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about Java ORM framework and DAO framework how to carry out Fast-Dao, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article, without saying much, follow the editor to have a look.
Greatly simplify DAO operation, object-oriented database operation, and greatly improve coding efficiency
Support for custom SQL
Support for Spring transaction management and manual transactions
Supports distributed cache and local cache, and allows data to actively refresh the cache after addition, deletion and modification.
Example
User user = UserFastDao.create () .dao () .insert (user); / / add, after the addition, the primary key will set Integer delCount = UserFastDao.create () .id (1) .dao () .delete (); / / delete, you can choose logical deletion and physical deletion Integer updateCount = UserFastDao.create () .id (1) .dao () .update (user) / / change, simple operation, rich conditions PageInfo page = UserFastDao.create (). Dao (). FindPage (1, 10); / / check, paging query 1. Frame installation 1.1 Maven address com.fast-dao fast-dao LATEST1.2 Framework configuration / * Field Hump conversion example user_name = userName enabled by default * / FastDaoConfig.openToCamelCase () / * set SQL log printing, off by default * Parameter 1: log print level DEBUG,INFO,OFF * Parameter 2: whether to print detailed SQL logs * Parameter 3: whether to print SQL execution results * / FastDaoConfig.openSqlPrint (SqlLogLevel.INFO,true, true) / * enable automatic creation time setting for new data operations * Parameter 1: field name that needs to set creation time * / FastDaoConfig.openAutoSetCreateTime ("create_time"); / * * enable automatic update time setting for data update operation / logical deletion operation * Parameter 1: field name for which update time needs to be set * / FastDaoConfig.openAutoSetUpdateTime ("update_time") / * enable the logical deletion function. When it is enabled, the data marked by logical deletion will be updated | deleted | protected during query. You can perform a single operation through the template to disable logical deletion protection * Parameter 1: logical deletion field name * Parameter 2: logical deletion tag default value * / FastDaoConfig.openLogicDelete ("deleted", Boolean.TRUE) / * set the global default cache time, two cache modes (local cache, Redis cache), and automatically refresh the cached data after automatic refresh of the cache. * Reids cache needs to be configured * Parameter 1: default cache time * Parameter 2: default cache time type * / FastDaoConfig.openCache (10L, TimeUnit.SECONDS) / * data source configuration, Spring environment can automatically identify * / FastDaoConfig.dataSource (dataSource) without setting; / * redis cache configuration, Spring environment can automatically identify * / FastDaoConfig.redisConnectionFactory (redisConnectionFactory) without setting; 1.3 file generation FileCreateConfig config = new FileCreateConfig () / * set database connection information * @ param url database connection * @ param user user name * @ param password password * @ param driverClass database driver * / config.setDBInfo ("jdbc:mysql://IP: port / database? useUnicode=true&characterEncoding=utf-8&useInformationSchema=true", "account", "password", "driver (example: com.mysql.cj.jdbc.Driver)") / * package path to generate template * @ param basePackage package path address xxx.xxx.xxx * / config.setBasePackage ("xxx.xxx.xxx"); / * template file types to be generated, using FileCreateConfig.CodeCreateModule enumeration, multiple * @ param modules template file types separated by commas * / config.setNeedModules (FileCreateConfig.CodeCreateModule.Base) / * whether to filter table prefix information * @ param prefix whether to filter table prefix information when generating files, and whether ord_orders = orders * @ param prefixFileDir generates different file directories through prefix information. Ord_orders will specify a prefix for storing the template generated by orders in the ord directory * @ param prefixName filter, if you do not specify to pass null * / config.setPrefix (false,false,null) / * * whether to use Lombok plug-in annotations * @ param useLombok default false * / config.setUseLombok (false); / * whether to generate Swagger2 annotations on DTO * @ param useDTOSwagger2 default false * / config.setUseDTOSwagger2 (false); / * whether to underline fields and generated objects, such as product_sku = ProductSku * @ param underline2CamelStr default true * / config.setUnderline2CamelStr (true) / * * whether to overwrite the old file * @ param replaceFile default true * / config.setReplaceFile (true); / * the name of the table to be generated is * @ param tables. Multiple tables are separated by commas. If you need to generate all tables in the database, the parameter is all * / config.setCreateTables ("all"). / * if it is a multi-module project, you need to use this * @ param childModuleName to specify under which module to create the template file * / config.setChildModuleName ("module name"); / / generate code TableFileCreateUtils.create (config); 2. Usage instructions / / use example FastUserTestFastDAO query = new FastUserTestFastDAO (); query.userName (). LikeRight ("Zhang"); query.age (). Less (30); query.createTime (). OrderByDesc (); List userList = query.dao (). FindAll (); 2.1 condition setting / / file generation object UserFastDao fastDao = new UserFastDao (); functional method example equality condition setting fastDao.fieldName (parameter.)
FastDao.fieldName () .notValEqual (parameter) fastDao.userName (Zhang San, Li Si)
FastDao.userName (). NotValEqual ("Zhang San") fuzzy matching condition setting fastDao.fieldName (). Like (parameter)
FastDao.fieldName () .likeLeft (parameter)
FastDao.fieldName () .likeRight (parameter)
FastDao.fieldName () .notLike (parameter)
FastDao.fieldName () .notLikeLeft (parameter)
FastDao.fieldName (). NotLikeRight (parameter) fastDao.userName (). Like (Zhang)
FastDao.userName (). LikeLeft (Zhang)
FastDao.userName (). LikeRight ("three")
FastDao.userName (). NotLike (Zhang)
FastDao.userName (). NotLikeLeft (Zhang)
FastDao.userName (). NotLikeRight ("three") IN condition setting fastDao.fieldName (). In ("parameter 1"...)
FastDao.fieldName (). NotIn ("parameter 1"...) fastDao.userName (). In ("Zhang San", "Li Si")
FastDao.userName (). NotIn ("Zhang San", "Li Si") range condition sets fastDao.fieldName (). Between (min, max)
FastDao.fieldName () .notBetween (min, max) fastDao.age () .between (20,30)
FastDao.age () .notBetween 30) greater than the conditional setting fastDao.fieldName (). Greater (parameter) fastDao.age (). Greater (30) greater than or equal to the conditional setting fastDao.fieldName (). GreaterOrEqual (parameter) fastDao.age (). GreaterOrEqual (30) is less than the conditional setting fastDao.fieldName (). Less (parameter) fastDao.age (). Less (10) is less than or equal to the conditional setting fastDao.fieldName (). LessOrEqual (parameter) fastDao.age (). LessOrEqual (10) IsNull conditional settings fastDao .fieldName () .isNull () fastDao.userName () .isNull () NotNull condition settings fastDao.fieldName () .notNull () fastDao.userName () .notNull () sort settings-ascending order fastDao.fieldName () .orderByAsc () fastDao.age () .orderByAsc () sort settings-descending order fastDao.fieldName () .orderByDesc () fastDao.age () .orderByDesc () object condition settings fastDao.equalObject (object) User user = new User
User.setName ("Zhang San")
FastDao.equalObject (user)
Query specified field settings fastDao.fieldName (). ShowField () query only the specified fields when performing the query operation, and multiple fields can be set
FastDao.id () .showField ()
FastDao.userName (). ShowField (); filter field settings fastDao.fieldName (). HideField () query operation does not query the specified fields, but can set multiple
FastDao.password () .hideField ()
FastDao.mail () .hideField () Field to repeatedly set fastDao.fieldName (). DistinctField () fastDao.userName (). DistinctField () field to sum fastDao.fieldName (). SumField () fastDao.age (). SumField () field to find the average setting fastDao.fieldName (). AvgField () fastDao.age (). AvgField () field to find the minimum setting fastDao.fieldName (). MinField () fastDao.age (). MinField () field to find the maximum setting fastDao.fieldName (). MaxField () fastDao.age (). MaxField () field custom update settings fastDao.fieldName (). CustomizeUpdateValue () is equivalent to age=age+5
At the same time, you can set other update conditions or update parameters
FastDao.age () .customizeUpdateValue () .thisAdd ("# {age}", Collections.singletonMap ("age", 5)) .dao () .update (null) Custom SQL condition Settings fastDao.andSql (SQL statement, parameters)
FastDao.orSql (SQL statements, parameters)
FastDao.sql (SQL statements, parameters) splices custom SQL statements after WHERE
If there are placeholder parameters, you need to declare using # {parameter name}
Pass parameter MAP collection put (parameter name, parameter value)
Map params = new HashMap ()
Params.put ("userName", "Zhang San")
FastDao.andSql ("userName = # {userName}", params) disable logical deletion protection fastDao.closeLogicDeleteProtect () will close this execution with logical deletion protection
After closing, all actions will affect the data marked by logical deletion OR condition setting fastDao.fieldName (). Or () specifies the field OR condition setting
Example: the condition is that the name is equal to Zhang San or null
FastDao.userName (). ValEqual ("Zhang San"). Or (). IsNull () 2.2 Dao actuator
The Dao executor calls:
/ / File generation object FastDao dao = UserFastDao.create () .dao ()
Actuator method:
Explain the method name example add Pojo insert (Pojo pojo) add a user, after the addition is successful, the object primary key field will be assigned.
User user = UserFastDao.create () .dao () .insert (user) query single data Pojo findOne () query information named Zhang San
User user = UserFastDao.create (). UserName ("Zhang San"). Dao (). FindOne () query multiple data List findAll () query all users aged between 20 and 30
List list = UserFastDao.create (). Age (). Between (20. 30). Dao (). FindAll () number of queries Integer findCount () query total number of users
Integer count = UserFastDao.create (). Dao (). FindCount () paging query PageInfo findPage (int pageNum, int pageSize) paging query users, and sort the age
PageInfo page = UserFastDao.create (). Age (). OrderByDesc (). FindPage (1, 10) updates the data. Attributes with empty parameters in the object are not updated. Integer update (Pojo pojo) updates users named Zhang San and Li Si.
Integer count = UserFastDao.create (). UserName (). In ("Zhang San", "Li Si"). Dao (). Update (user) updates the data, and the attributes with empty parameters in the object are also updated. Integer updateOverwrite (Pojo pojo) updates users whose age is less than 30 and whose surname is Zhang.
UserFastDao fastDao = UserFastDao.create ()
FastDao.age (). Less (30)
FastDao.userName (). Like (Zhang)
Integer count = fastDao.updateOverwrite (user) physically deleted by conditional
If the logical delete function is enabled
This operation will automatically delete the data tag modification, will not be physically deleted
Unless logical deletion protection is turned off
Logically delete configuration
FastDaoConfig.openLogicDelete ("deleted", true)
To turn off the protection mode of logical deletion, please refer to the condition settings.
Important! Users over 80 or null will be deleted using physical deletion method Integer delete () if no settings are made.
Integer count = UserFastDao.create () .age () .greater (80) .or () .isNull () .delete () 2.3Custom SQL
Complex SQL operations such as multiple tables can be implemented using custom SQL executors, and the framework automatically maps objects and tables.
If any parameter needs to be declared using # {parameter name}, pass the put (parameter name, parameter value) in the parameter MAP collection
FastCustomSqlDao.create (Class, SQL statements, parameters)
/ example: String sql = "SELECT * FROM user WHERE `user_ name` LIKE # {userName}"; HashMap params = new HashMap (); params.put ("userName", "% Zhang Yawei%"); List all = FastCustomSqlDao.create (User.class, sql, params). FindAll ()
When caching is enabled, caching can be enabled by adding annotations to Bean.
/ * * Redis cache * when adding, updating or deleting operations using this framework template, the data in the Redis cache will be automatically refreshed * the default parameter is the cache time and type set by the frame * cache optional parameters * FastRedisCache (Long seconds) such as @ FastRedisCache (60L) cache 60 seconds * FastRedisCache (cacheTime = time, cacheTimeType = TimeUnit) such as @ FastRedisCache (cacheTime = 1L) CacheTimeType = TimeUnit.HOURS) cache for 1 hour * / @ FastRedisCache/** 1. Memory cache 2. When caching is turned on and the object is configured to configure this annotation, the queried data will be cached locally. When you add, update, or delete operations using this framework template, the cached data in memory will be automatically refreshed. The default parameter is the cache time and type 5. 0 set by the frame. Cache optional parameter 6. FastStatisCache (Long seconds) such as @ FastStatisCache (60L) cache 60 seconds 7. FastStatisCache (cacheTime = time, cacheTimeType = TimeUnit) such as @ FastStatisCache (cacheTime = 1L cacheTimeType = TimeUnit.HOURS) cache 1 hour * / @ FastStatisCache2.5 data source switch
The data source can be replaced at any one execution, and the change of the data source only affects the current thread
/ example FastDaoConfig.dataSource (getDataSource ()); / change the global data source FastDaoConfig.dataSourceThreadLocal (getDataSource ()); / / replace the thread data source private static DataSource getDataSource () {DruidDataSource dataSource = new DruidDataSource (); dataSource.setUrl ("jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC"); dataSource.setUsername ("root"); dataSource.setPassword ("123456") DataSource.setDriverClassName ("com.mysql.cj.jdbc.Driver"); return dataSource;} 2.6Section
Using section, you can perform many custom operations, such as read-write separation, adding parameters when CRUD, permission verification, etc.
2.6.1 implement FastDaoExpander interface public class DemoExpander implements FastDaoExpander {/ * @ param param encapsulates all the execution parameters of DAO * @ return whether to execute * / @ Override public boolean before (FastDaoParam param) {System.out.println ("before DAO execution"); return true } / * * @ param param encapsulates all DAO execution parameters * / @ Override public void after (FastDaoParam param) {System.out.println ("after DAO execution");} @ Override public List occasion () {/ / configure DAO section execution timing List list = new ArrayList (); list.add (ExpanderOccasion.SELECT); list.add (ExpanderOccasion.UPDATE) Return list;}} 2.6.2 configure aspect implementation, you can add multiple aspects FastDaoConfig.addFastDaoExpander (DemoExpander.class); 2.7 Manual transaction management FastTransaction.open (); / / Open transaction FastTransaction.commit (); / / commit FastTransaction.rollback (); / / rollback / / sample FastTransaction.open (); / / Open transaction FastUserTestFastDao.create (). Dao (). Insert (user); / / add data FastTransaction.commit () / / submit the above is how Java's ORM framework and DAO framework implement Fast-Dao. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.