@Override public void addAdvert(AdvertDTO advertDto) { //MediaFile mediaFile = new MediaFile(); AdPosition adPosition = Optional.ofNullable(adPositionMapper.selectByPrimaryKey(advertDto.getPositionId())) .orElseThrow(() -> new RuntimeException("没有找到对应的广告位置")); Advert advert = Advert.builder() .name(advertDto.getName()) .position(adPosition) .media(advertDto.getMediaFile()) .startDate(advertDto.getStartDate()) .endDate(advertDto.getEndDate()) .link(advertDto.getLink()) .status(advertDto.getStatus()) .build(); AdvertMapper.insertSelective(advert); } @Override public void updateAdvert(Integer id, AdvertDTO advertDto) { AdPosition adPosition = Optional.ofNullable(adPositionMapper.selectByPrimaryKey(advertDto.getPositionId())) .orElseThrow(() -> new RuntimeException("Ad position not found")); Advert advert = Advert.builder() .name(advertDto.getName()) .position(adPosition) .media(advertDto.getMediaFile()) .startDate(advertDto.getStartDate()) .endDate(advertDto.getEndDate()) .link(advertDto.getLink()) .status(null != advertDto.getStatus() ? advertDto.getStatus() : 0) .build(); AdvertMapper.insert(advert); },如何优化代码

时间: 2024-02-14 17:05:20 浏览: 25
首先需要注意的是,在 updateAdvert 方法中,我们应该使用 updateByPrimaryKeySelective 方法而不是 insert 方法,因为我们只需要更新部分字段而不是全部字段。 另外,在两个方法中,我们可以使用 AdvertMapper 的自动生成代码中的 updateByExampleSelective 方法和 insertSelective 方法,这样可以减少手动编写 SQL 语句的工作量,也可以更简洁地实现相同的功能。 最后,我们可以将 Optional.ofNullable().orElseThrow() 的代码块提取出来作为一个方法,这样可以使代码更加简洁易读,也可以提高代码的复用性。 综上所述,下面是优化后的代码示例: ``` private AdPosition getAdPositionById(Integer positionId) { return Optional.ofNullable(adPositionMapper.selectByPrimaryKey(positionId)) .orElseThrow(() -> new RuntimeException("Ad position not found")); } @Override public void addAdvert(AdvertDTO advertDto) { Advert advert = Advert.builder() .name(advertDto.getName()) .position(getAdPositionById(advertDto.getPositionId())) .media(advertDto.getMediaFile()) .startDate(advertDto.getStartDate()) .endDate(advertDto.getEndDate()) .link(advertDto.getLink()) .status(advertDto.getStatus()) .build(); advertMapper.insertSelective(advert); } @Override public void updateAdvert(Integer id, AdvertDTO advertDto) { Advert advert = Advert.builder() .name(advertDto.getName()) .position(getAdPositionById(advertDto.getPositionId())) .media(advertDto.getMediaFile()) .startDate(advertDto.getStartDate()) .endDate(advertDto.getEndDate()) .link(advertDto.getLink()) .status(null != advertDto.getStatus() ? advertDto.getStatus() : 0) .build(); AdvertExample example = new AdvertExample(); example.createCriteria().andIdEqualTo(id); advertMapper.updateByExampleSelective(advert, example); } ```

相关推荐

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ipEditText = findViewById(R.id.ipEditText); portEditText = findViewById(R.id.portEditText); Button connectButton = findViewById(R.id.connectButton); connectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String ip = ipEditText.getText().toString(); int port = Integer.parseInt(portEditText.getText().toString()); new ConnectTask().execute(ip, String.valueOf(port)); } }); Button sendMessageButton = findViewById(R.id.sendMessageButton); sendMessageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showSendMessageDialog(); } }); } private class ConnectTask extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params) { String ip = params[0]; int port = Integer.parseInt(params[1]); try { socket = new Socket(ip, port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); // 在 UI 线程中创建 SeekBar handler.post(new Runnable() { @Override public void run() { SeekBar progressBar = findViewById(R.id.progressBar); progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // 计算百分比对应的数字 int number = progress * 10; // 在 UI 线程中更新 ProgressBar 的进度 handler.post(new Runnable() { @Override public void run() { seekBar.setProgress(number); } }); out.println(number); } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) {} }); } }); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { // 在连接结束后做一些处理 // 比如关闭连接或者显示连接成功的提示 } }代码修改

private EditText ipEditText; private EditText portEditText; private TextView messageTextView; private BufferedReader in; private PrintWriter out; private Socket socket; private Handler handler = new Handler(); @SuppressLint("MissingInflatedId") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ipEditText = findViewById(R.id.ipEditText); portEditText = findViewById(R.id.portEditText); Button connectButton = findViewById(R.id.connectButton); connectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String ip = ipEditText.getText().toString(); int port = Integer.parseInt(portEditText.getText().toString()); new ConnectTask().execute(ip, String.valueOf(port)); } }); Button sendMessageButton = findViewById(R.id.sendMessageButton); sendMessageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showSendMessageDialog(); } }); } private class ConnectTask extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params) { String ip = params[0]; int port = Integer.parseInt(params[1]); try { socket = new Socket(ip, port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); // 获取SeekBar对象 SeekBar progressBar = findViewById(R.id.progressBar); // 添加OnSeekBarChangeListener监听器 progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // 计算百分比对应的数字 int number = progress * 10; int tnum = 0; tnum = number; out.println(tnum); } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) {} }); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } @Override protected void onDestroy() { super.onDestroy(); try { if (in != null) { in.close(); } if (out != null) { out.close(); } if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } private void showSendMessageDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.dialog_send_message, null); final EditText messageEditText = view.findViewById(R.id.messageEditText); builder.setView(view) .setTitle("发送消息") .setPositiveButton("发送", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String message = messageEditText.getText().toString(); if (out != null) { new Thread(new Runnable() { @Override public void run() { out.println(message); } }).start(); } } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create() .show(); }代码有问题,修改一下

能补充这段代码吗import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Polygon; import javafx.stage.Stage; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; abstract class Shape { protected Color color; protected double area; protected double perimeter; protected double positionX; protected double positionY; public abstract void calculateArea(); public abstract void calculatePerimeter(); public abstract void draw(Pane pane); public void setPosition(double x, double y) { this.positionX = x; this.positionY = y; } } class CircleShape extends Shape { private double radius; public CircleShape(double radius) { this.radius = radius; this.color = Color.RED; } @Override public void calculateArea() { this.area = Math.PI * Math.pow(radius, 2); } @Override public void calculatePerimeter() { this.perimeter = 2 * Math.PI * radius; } @Override public void draw(Pane pane) { Circle circle = new Circle(radius); circle.setFill(color); circle.setLayoutX(positionX); circle.setLayoutY(positionY); pane.getChildren().add(circle); } } class RectangleShape extends Shape { private double width; private double height; public RectangleShape(double width, double height) { this.width = width; this.height = height; this.color = Color.BLUE; } @Override public void calculateArea() { this.area = width * height; } @Override public void calculatePerimeter() { this.perimeter = 2 * (width + height); } @Override public void draw(Pane pane) { Rectangle rectangle = new Rectangle(width, height); rectangle.setFill(color); rectangle.setLayoutX(positionX); rectangle.setLayoutY(positionY); pane.getChildren().add(rectangle); } } class TriangleShape extends Shape { private double[] points; public TriangleShape(double[] points) { this.points = points; this.color = Color.GREEN; } @Override public void calculateArea() { double x1 = points[0]; double y1 = points[1]; doubl

优化这个方法:private void saveFileBrowseRecord(LayoutElementParcelable file) { // 当前的目录 String currentPath = file.desc.substring(0, file.desc.lastIndexOf(File.separator)); String basePath = mSourceRootPath; if (mTransferType == U_FTP_TO_FAB_FTP) { basePath = mSourcePath; } XLog.tag(TAG).i("mCurrentPath:" + currentPath + " basePath:" + basePath); HybridFileParcelable hybridFileParcelable = new HybridFileParcelable(currentPath, basePath, file.desc, file.permissions, file.date, file.longSize, file.isDirectory, file.getMode(), ""); if (!TextUtils.isEmpty(file.title)) { hybridFileParcelable.setName(file.title); } Map<String, Object> map = new HashMap<>(); // 文件路径全名称 map.put("dirFullName", hybridFileParcelable.getRelativePath()); // 文件服务器id map.put("fileServerId", mStoreServerId); RequestBody body = HttpClient.getRequestBody(map); TransferApi api = HttpClient.api(TransferApi.class, false); if (api == null) { XLog.tag(TAG).i("save file browse record api is null"); return; } // recordType 记录类型:默认0-最近浏览,1-收藏 api.saveFileBrowseRecord(body, 1) .compose(HttpClient.observableIoToMain()) .as(HttpClient.bindLifecycle(this)) .subscribe(new HttpDefaultObserver<HttpResult<String>>() { @Override public void start() { } @Override public void success(HttpResult<String> result) { mCollects.put(file.desc, file.desc); } @Override public void fail(HttpError e) { showWhiteFailToast(e.getCode(), e.getMessage(), null); } @Override public void finish() { } }); }

最新推荐

recommend-type

k8s1.16的jenkins部署java项目cicd(cd手动)-kubernetes安装包和详细文档笔记整理

k8s1.16的jenkins部署java项目cicd(cd手动)-kubernetes安装包和详细文档笔记整理
recommend-type

sja1311.x86_64.tar.gz

SQLyong 各个版本,免费下载 SQLyog是业界著名的Webyog公司出品的一款简洁高效、功能强大的图形化MySQL数据库管理工具。使用SQLyog可以快速直观地让您从世界的任何角落通过网络来维护远端的MySQL数据库。
recommend-type

debugpy-1.1.0-cp34-cp34m-manylinux1_x86_64.whl

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

SQLyog-12.5.0-0.x64Community.exe

SQLyog-12.5.0-0.x64Community
recommend-type

debugpy-1.0.0b12-cp35-cp35m-manylinux1_i686.whl

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

用Spring boot和vue写一个登录注册界面

好的,这是一个比较常见的技术问题,我可以为您提供一些参考资料和思路。首先,您可以使用Spring Boot作为后端框架来处理用户认证和注册的逻辑,比如使用Spring Security实现用户登录认证。同时,您还需要设计相应的数据模型和数据库表结构来存储用户信息。在前端方面,您可以使用Vue.js作为框架来构建登录注册页面,使用Axios来发起API请求并和后端进行交互。当然,在实现过程中,还需要考虑一些具体细节,比如数据校验、安全性和用户体验等方面。希望这些信息能够帮助到您。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。